Files
Python_CookBook_repo/4.迭代器与生成器/7.对迭代器做切片操作.py
2025-09-10 16:12:45 +08:00

27 lines
874 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from itertools import islice
if __name__ == '__main__':
# 在程序生成过程中,我们有时候需要做一些无限生成器,这些生成器往往需要切片使用
def infinity_iterator(start):
while True:
yield start
start += 1
# 无限生成器
for i in infinity_iterator(0):
print(i)
break
# 想要对无限生成器进行切片我们就需要使用itertools里的islice函数,记得这个函数也是左闭右开
iterator= infinity_iterator(0)
iter_10_20 = islice(infinity_iterator(0), 10, 21)
for i in iter_10_20:
print(i)
# 注意islice操作是通过丢弃索引序列前的元素实现的返回的是一个一次性迭代器被迭代过后元素就被消耗掉无了
print("再次使用迭代")
for i in iter_10_20:
print(i)