如何从无限生成器列表中获取第一个n元素?

2024-06-16 13:16:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个无限发电机:

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]

Tags: 方法intrue元素fordefcountls
2条回答

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)))

为了回答@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])

Output:

[1, 2, 3, 4, 5]

相关问题 更多 >