我有这个无限生成器:
def infiniList():
count = 0
ls = []
while True:
yield ls
count += 1
ls.append(count)
有没有办法采用前n个元素?我的意思是,我做到了:
n = 5
ls = infiniList()
for i in range(n):
rs = next(ls)
输出:
print(rs)
[1, 2, 3, 4]
答案 0 :(得分:1)
itertools.islice
确实做到了这一点,尽管在您的示例中,您需要注意不要重复产生对不断修改的同一对象的引用:
def infiniList():
count = 0
ls = []
while True:
yield ls[:] # here I added copying
count += 1
ls.append(count) # or you could write "ls = ls + [count]" and not need to make a copy above
import itertools
print(list(itertools.islice(infiniList(), 5)))
答案 1 :(得分:0)
仅需介绍@NPE的良好答案,我需要做的就是:
import itertools
def infiniList():
count = 0
ls = []
while True:
yield ls
count += 1
ls = ls + [count]
print(list(itertools.islice(infiniList(), 5, 6))[0])
输出:
[1, 2, 3, 4, 5]