因为reversed()
返回迭代而sorted()
返回一个新的列表。
,你得到sorted()
后面的名单是相等的名单:
>>> a = [1, 2, 3]
>>> sorted(a)
[1, 2, 3]
>>> sorted(a)
[1, 2, 3]
>>> sorted(a) == sorted(a) # The equality here is checking that the lists contain the same objects in the same order
True
>>> sorted(a)[0] is sorted(a)[0]
True
>>> sorted(a) is sorted(a) # However, they are not the same lists, modifying one will not modify the other
False
,你得到reversed()
后面的迭代器将是不同的每次调用时间:
>>> a = [1, 2, 3]
>>> reversed(a)
<listreverseiterator object at 0x01C2A9D0>
>>> reversed(a)
<listreverseiterator object at 0x01AB4EF0>
消费其中一个迭代器两次会导致它第二次产生一个空列表,如您在最后一个示例中所见:
>>> a = [1, 2, 3]
>>> b = reversed(a)
>>> list(b)
[3, 2, 1]
>>> list(b)
[]
>>>
名
,我们找回了迭代器的这些空列表将解释第二〔实施例:
>>> b= reversed(a)
# The first sorted(b) is the real sorted list, the second one is an empty list because the iterator has been consumed
>>> sorted(b)==sorted(b)
False
# Now both of our sorted(b) are just empty lists, since the iterator has been consumed
>>> sorted(b)==sorted(b)
True
你只有30秒快;)无论如何,删除它。 –
“你从sort()返回的列表在每次调用时都是同一个对象” - 不正确。 – user2357112
@ user2357112 Ty,更正它们不是同一个对象,但它们是相同的列表 – Jkdc