因爲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