默认的Python排序方式是按字母顺序排列
给定:
>>> 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]
根据“the wolf”的评论,您还可以进行以下操作:
>>> sorted(c,key = lambda e: (isinstance(e, (float, int)), e))
['Z', 'a', 'abc', 'b', 'c', 'd', 0, 1, 2, 3, 4, 33, 33.333]
我必须同意这更好...
TypeError: unorderable types: int() < str()
的错误提示。 - Kevin