为什么我不能反转 Python 3 中的所有迭代器?

Why Can't I Reverse All Iterators in Python 3?

为什么我可以在列表和 range_iterator 上调用 reversed,但不能在 list_iterator 或 itertools 迭代器上调用?

>>> reversed(itertools.accumulate(reversed(x), lambda x, y: x + y))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'itertools.accumulate' object is not reversible

如果你 read the docs 你会发现 reversed 适用于具有以下特征的任何对象:

has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0)

注意,这意味着 不能 在 range_iterator 上使用 reversed,但可以在常规 range 对象上使用。

>>> reversed(iter(range(10)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'range_iterator' object is not reversible
>>> reversed(range(10))
<range_iterator object at 0x105bcac90>

另请注意,您通常根本无法反转 iterators,通常可反转的是 sequence-like iterables。或者任何通过魔术方法钩子 __reversed__() 支持它的东西,而迭代器通常两者都没有(通常只支持 __iter____next__