默认的 Python 排序是asciibetical
给定:
>>> c = ['c', 'b', 'd', 'a', 'Z', 0, 4, 2, 1, 3]
默认排序为:
>>> sorted(c)
[0, 1, 2, 3, 4, 'Z', 'a', 'b', 'c', 'd']
它在 Python3 上也完全不起作用:
Python 3.4.3 (default, Feb 25 2015, 21:28:45)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> c = ['c', 'b', 'd', 'a', 'Z', 0, 4, 2, 1, 3]
>>> sorted(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < str()
解决方案是创建一个元组,其中索引整数作为第一个元素(基于项目类型),项目本身作为下一个元素。 Python 2 和 3 将对具有第二个元素异构类型的元组进行排序。
给定:
>>> c = ['c', 'b', 'd', 'a', 'Z', 'abc', 0, 4, 2, 1, 3,33, 33.333]
注意字符、整数、字符串、浮点数的混合
def f(e):
d={int:1, float:1, str:0}
return d.get(type(e), 0), e
>>> sorted(c, key=f)
['Z', 'a', 'abc', 'b', 'c', 'd', 0, 1, 2, 3, 4, 33, 33.333]
或者,如果你想要一个 lambda:
>>> sorted(c,key = lambda e: ({int:1, float:1, str:0}.get(type(e), 0), e)))
['Z', 'a', 'abc', 'b', 'c', 'd', 0, 1, 2, 3, 4, 33, 33.333]
根据“狼”的评论,你也可以这样做:
>>> sorted(c,key = lambda e: (isinstance(e, (float, int)), e))
['Z', 'a', 'abc', 'b', 'c', 'd', 0, 1, 2, 3, 4, 33, 33.333]
我必须同意的更好......