python迭代器&生成器使用技巧:切片遍历索引值多序列多容器对象
发布时间
阅读量:
阅读量
1. 迭代器切片
迭代器与生成器无法应用常规的切片操作,原因在于其长度无法预先确定(同时未实现索引功能)。islice() 函数能够生成一个迭代器,该迭代器可按需提取特定元素,其工作原理为:首先逐个跳过直至切片起始索引位置的所有元素,随后依次返回所需元素,直至抵达切片终止索引位置。
import itertools
def count(n):
while True:
yield n
n += 1
c = count(0)
# print( c[10:20] )
# TypeError: 'generator' object is not subscriptable
for num in itertools.islice(c, 10, 15):
print(num)
# >>> 10, 11, 12, 13, 14
全部评论 (0)
还没有任何评论哟~
