跟进这个问题: Sort when values are None or empty strings python 我正在寻找Python 3中一个完全可行的解决方案。
在Python 2.7.6中,我可以成功地执行以下操作:
> list_with_none = [(1,"foo"), (2,"bar"), (3,""), (4,None), (5,"blub")]
> col = 1
> sorted(list_with_none, key=lambda k: (k[col] is None, k[col] == "", k[col]))
[(2, 'bar'), (5, 'blub'), (1, 'foo'), (3, ''), (4, None)]
> sorted(list_with_none, key=lambda k: (k[col], k[col] is None, k[col] == ""), reverse=True)
[(1, 'foo'), (5, 'blub'), (2, 'bar'), (3, ''), (4, None)]
在Python 3.4.3中,我找不到反向排序的工作解决方案,它在列表的末尾放置空字符串和None值(这是我明确需要的):
> list_with_none = [(1,"foo"), (2,"bar"), (3,""), (4,None), (5,"blub")]
> col = 1
> sorted(list_with_none, key=lambda k: (k[col] is None, k[col] == "", k[col]))
[(2, 'bar'), (5, 'blub'), (1, 'foo'), (3, ''), (4, None)]
> sorted(list_with_none, key=lambda k: (k[col], k[col] is None, k[col] == ""), reverse=True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: NoneType() < str()
答案 0 :(得分:2)
传递reverse=True
时,反转None
和空字符串的检查:
sorted(list_with_none, key=lambda k: (k[col] is not None, k[col] != "", k[col]), reverse=True)
这适用于Python 2以及Python 3。
答案 1 :(得分:1)
你关心的是,如果值为None或不是None,那么只有两个条件重要
print(sorted(list_with_none, key=lambda x: (x[1] is not None, x[1]), reverse=True))