如何生成一个iterable除最后几个值以外的所有值?

2024-04-20 15:50:55 发布

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

假设我必须定义一个函数,它接受一个iterable并生成除最后5个以外的所有值。到现在为止,我有这样的东西:

def generate_all_but_5(iterable):
    x = iter(iterable)
    list_of_current = []
    try:
        while True:
            list_of_current.append(next(x))
    except StopIteration:
        pass
    for y in list_of_current[:-5]:
        yield y

这是可行的,但是我不能像这里那样将iterable的所有值复制到一个列表中,因为可能有无限多的值。有没有其他方法可以在不首先将所有内容添加到列表中的情况下实现解决方案?你知道吗


Tags: of函数true列表定义defcurrentall
1条回答
网友
1楼 · 发布于 2024-04-20 15:50:55

我假设在内存中只保存5项就可以了。你可以试试这个:

def generate_all_but_5(iterable):
    x = iter(iterable)
    list_of_current = []
    for i, item in enumerate(x):
        list_of_current.append(item)
        if i >= 5:
            yield list_of_current.pop(0)

它首先从iterable中加载5个条目,然后弹出并生成列表的前面并附加下一个条目。最后五个仍然在list_of_current中,不会是收益率。你知道吗

list(generate_all_but_5(range(6)))
# [0]
list(generate_all_but_5(range(10)))
# [0, 1, 2, 3, 4]
list(generate_all_but_5('Hello world!'))
# ['H', 'e', 'l', 'l', 'o', ' ', 'w']

注意,这样做的副作用是,虽然最后5个不会从generate_all_but_5返回,但它们仍然会从传入的iterable中弹出。既然你没有提到保持最后5个在iterable不变,我想没有这样的要求。你知道吗

说明:

让我们在for循环中打印list_of_current,看看发生了什么。你知道吗

def generate_all_but_5(iterable):
    x = iter(iterable)
    list_of_current = []
    for i, item in enumerate(x):
        print(list_of_current) # print the list
        list_of_current.append(item)
        if i >= 5:
            yield list_of_current.pop(0)

g = generate_all_but_5(range(8))
n = next(g)
# []
# [0]
# [0, 1]
# [0, 1, 2]
# [0, 1, 2, 3]
# [0, 1, 2, 3, 4]
# n = 0
n = next(g)
# [1, 2, 3, 4, 5]
# n = 1
n = next(g)
# [2, 3, 4, 5, 6]
# n = 2
n = next(g)
# StopIteration Error

最后一次屈服后,list_of_current == [3, 4, 5, 6, 7]。最后5项都在列表中,表中没有剩余项。你知道吗

我不善于解释事情。我希望这个例子有帮助!你知道吗

相关问题 更多 >