美文网首页
python itertools islice对迭代器做切片操作

python itertools islice对迭代器做切片操作

作者: 孙广宁 | 来源:发表于2022-05-15 18:44 被阅读0次
4.7 如何对迭代器和生成器做切片操作。
>>> def c(n):
...     while True:
...         yield n
...         n+=1
...
>>> c = c(0)
>>> c
<generator object c at 0x104beff50>
>>> c[10:20]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'generator' object is not subscriptable
>>>
>>> import itertools
>>> for x in itertools.islice(c,10,20):
...     print(x)
...
10
11
12
13
14
15
16
17
18
19
>>>
  • 综上,普通的迭代器和生成器无法执行普通的切片操作,这是因为不知道他们的长度是多少
  • islice函数产生的结果是一个迭代器,它可以得到想要的切片元素
  • islice会消耗掉迭代器中的数据,意思迭代器中的数据只能被访问一次
  • 所以在访问之前应该先将数据放到列表中

相关文章

网友评论

      本文标题:python itertools islice对迭代器做切片操作

      本文链接:https://www.haomeiwen.com/subject/yifwyrtx.html