在测试list()与reversed()结合时,碰到如下结果:
>>> a = '123 456'
>>> b = reversed(list(a.split()))
>>> b
<list_reverseiterator object at 0x0000000002D45FD0>
>>> list(b)
['456', '123']
>>> list(b)
[]
>>> list(b)
[]
>>> list(b)
[]
>>>
为什么reversed()之后,第二次及以后的list()得到的list都是空?google得到的解答如下:
解释一:
That’s because reversed creates an iterator, which is already spent when you’re calling list(bb) for the second time.解释二:
The reason is that b is not the reversed list itself, but a listreverseiterator. So when you call list() the first time, it iterates over b and creates a new list from the items output from that iterator. When you do it a second time, b is still the original iterator and has already gone through all the items, so it doesn’t iterate over anything, resulting in an empty list
python自带文档对于reversed()的描述如下:
reversed(seq)
Return a reverse iterator. seq must be an object which has a reversed() method or supports the sequence protocol (the len() method and the getitem() method with integer arguments starting at 0).
object.reversed(self)
Called (if present) by the reversed() built-in to implement reverse iteration. It should return a new iterator object that iterates over all the objects in the container in reverse order.If the reversed() method is not provided, the reversed() built-in will fall back to using the sequence protocol (len() and getitem()). Objects that support the sequence protocol should only provide reversed() if they can provide an implementation that is more efficient than the one provided by reversed().
即reversed()之后的iterator只在第一次遍历时返回值。