2015-12-08 135 views
1

這是代碼Python:爲什麼顛倒(a)==顛倒(a)返回False其中a是數組?

>>> a=[1,3,2] 
>>> a 
[1, 3, 2] 
>>> a= 3,1,2 
>>> a 
(3, 1, 2) 
>>> sorted(a) 
[1, 2, 3] 
>>> sorted(a)==sorted(a) 
True 
>>> reversed(a)==reversed(a) 
False 

而且

>>> b= reversed(a) 
>>> sorted(b)==sorted(b) 
False 
>>> sorted(b)==sorted(b) 
True 

我在一個YouTube視頻看到這並不能弄清楚發生了什麼。

那小子也顯示

>>> sorted(b) 
[] 

回答

0

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

你只有30秒快;)無論如何,刪除它。 –

+0

「你從sort()返回的列表在每次調用時都是同一個對象」 - 不正確。 – user2357112

+0

@ user2357112 Ty,更正它們不是同一個對象,但它們是相同的列表 – Jkdc

3

sorted返回一個新的,排序列表。 reversed返回一個反向迭代器。將兩個列表與相同的元素進行比較可以得出結論。比較兩個不同的迭代器不會。

如果要比較的反向迭代構建列表,你會得到True

>>> reversed(a) == reversed(a) 
False 
>>> list(reversed(a)) == list(reversed(a)) 
True 
+0

可以簡化爲:'名單(逆轉(一))==列表(逆轉(一))'。 .. –

+0

@IronFist好點。簡化。 – juanchopanza