跟进这个问题:当值是None或空字符串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()
通过时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。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句