对反转对象列表进行排序

时间:2016-10-20 22:48:18

标签: python sorting python-2.x

我正在寻找一种方法来进行反向 - lexicographical排序而不使用lameda函数,并且在使用reversed时注意到一些奇怪的事情:

>>> tuples = [
...    (1, 2, 3),
...    (2, 3, 1),
...    (3, 1, 2),
... ]
>>> sorted(tuples, key=reversed)
[(3, 1, 2), (2, 3, 1), (1, 2, 3)]  # wrong
>>> sorted(tuples, key=reversed)
[(2, 3, 1), (1, 2, 3), (3, 1, 2)]  # also wrong
>>> sorted(tuples, key=reversed)
[(2, 3, 1), (3, 1, 2), (1, 2, 3)]  # heyyy, third time lucky!

python如何对reversed个实例列表进行排序?

1 个答案:

答案 0 :(得分:1)

reversed对象的内存位置排序:

>>> x = reversed((1,2))
>>> y = reversed((2,1))
>>> sorted([x,y])
[<reversed at 0x7fffe84045d0>, <reversed at 0x7fffe84eb210>]
>>> sorted([y,x])
[<reversed at 0x7fffe84045d0>, <reversed at 0x7fffe84eb210>]

结果可以在后续运行时更改,因为每次都会分配新的reversed个对象。

但是,它是CPython implementation detail,并且在语言参考中无法保证。