我有这个无限发电机:
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)
Output:
print(rs)
[1, 2, 3, 4]
最佳答案
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)))
关于python - 如何从无限生成器列表中获取前 n 个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58355771/