默认的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]
或者,如果你想有一个拉姆达:基于
>>> 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]
我必须承认比较好...
警告:你的第三个例子也不会在Python 3工作。相反,你会得到'TypeError:无法定型的类型:int()
Kevin
2015-03-31 16:37:55