2015-12-08 98 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