我正在寻找一种方法来进行反向 - 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
个实例列表进行排序?
答案 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,并且在语言参考中无法保证。