Python:为什么reverse(a)== reverse(a)返回False,其中a是一个数组?

时间:2015-12-08 19:52:34

标签: python

这是代码

>>> 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)
[]

2 个答案:

答案 0 :(得分:3)

sorted返回一个新的排序列表。 reversed返回一个反向迭代器。比较具有相同元素的两个列表是否相等则为真。比较两个不同的迭代器不会。

如果你要比较用反向迭代器构造的列表,你会得到True

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

答案 1 :(得分: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
相关问题