sort of a
and b
are as expected to me, then why is c
different? Is there a ways to make it consistent with a
and b
, without converting everything to either lists or tuples?
对我来说有点像a和b,那为什么c不同?有没有办法使它与a和b保持一致,而不将所有内容都转换为列表或元组?
>>> a = [(1, 0), (0, 0)]
>>> a.sort()
>>> print a
[(0, 0), (1, 0)]
>>>
>>> b = [[1], (0)]
>>> b.sort()
>>> print b
[0, [1]]
>>>
>>> c = [[1, 0], (0, 0)]
>>> c.sort()
>>> print c
[[1, 0], (0, 0)]
>>>
2 个解决方案
#1
12
It's possible to convert them only for the purpose of sorting:
可以将它们转换为仅用于排序的目的:
>>> c = [[1, 0], (0, 0)]
>>> c.sort(key=tuple)
>>> c
[(0, 0), [1, 0]]
That being said, a list containing a mix of lists and tuples is a code smell.
话虽如此,包含列表和元组混合的列表是代码气味。
#2
0
If you are not sure whether the outermost container is a list, you might also want to use:
如果您不确定最外面的容器是否是列表,您可能还想使用:
sorted(c, key=tuple)
because c.sort() is a list-only function. Just thought I should add that.
因为c.sort()是一个仅列表函数。只是想我应该补充一点。
#1
12
It's possible to convert them only for the purpose of sorting:
可以将它们转换为仅用于排序的目的:
>>> c = [[1, 0], (0, 0)]
>>> c.sort(key=tuple)
>>> c
[(0, 0), [1, 0]]
That being said, a list containing a mix of lists and tuples is a code smell.
话虽如此,包含列表和元组混合的列表是代码气味。
#2
0
If you are not sure whether the outermost container is a list, you might also want to use:
如果您不确定最外面的容器是否是列表,您可能还想使用:
sorted(c, key=tuple)
because c.sort() is a list-only function. Just thought I should add that.
因为c.sort()是一个仅列表函数。只是想我应该补充一点。