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

2024-05-19 21:14:14 发布

您现在位置:Python中文网/ 问答频道 /正文

  • 我可以在列表中调用reversed。你知道吗
  • 我可以在范围迭代器上调用reversed。你知道吗
  • 我不能在列表迭代器上调用reversed。你知道吗
  • 我不能用电话打reverseditertools.com. 你知道吗

为什么我可以在列表和范围迭代器上调用reversed,而不能在列表迭代器或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

Tags: lambdacommost列表stdincallfileaccumulate
1条回答
网友
1楼 · 发布于 2024-05-19 21:14:14

如果您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迭代器上使用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>

另外请注意,通常根本不能反转迭代器,通常是像iterables那样的序列是可逆的。或者任何通过magic方法hook __reversed__()支持它的东西,迭代器通常两者都没有(通常只支持__iter____next__

相关问题 更多 >