如何在不中断循环的情况下 return 值?

How to return values without breaking the loop?

我想知道如何 return 值而不打破 Python 中的循环。

举个例子:

def myfunction():
    list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
    print(list)
    total = 0
    for i in list:
        if total < 6:
            return i  #get first element then it breaks
            total += 1
        else:
            break

myfunction()

return 只会得到第一个答案然后离开循环,我不想这样,我想 return 多个元素直到循环结束。

如何解决,请问有解决办法吗?

您可以为此创建一个 generator,这样您就可以从生成器中获取 yield 值(使用 yield 语句后,您的函数将成为一个生成器)。

查看以下主题以更好地了解如何使用它:

一个使用生成器的例子:

def simple_generator(n):
    i = 0
    while i < n:
        yield i
        i += 1

my_simple_gen = simple_generator(3) // Create a generator
first_return = my_simple_gen.next() // 0
second_return = my_simple_gen.next() // 1

您还可以在循环开始之前创建一个 list 并将 append 项目添加到该列表,然后 return 该列表,因此该列表可以被视为结果列表 "returned" 在循环中。

将列表用于 return 值的示例:

def get_results_list(n):
    results = []
    i = 0
    while i < n:
        results.append(i)
        i += 1
    return results


first_return, second_return, third_return = get_results_list(3)

注意: 在使用列表的方法中,您必须知道您的函数在 results 列表中 return 有多少值以避免 too many values to unpack错误

使用 generator 是一种可能的方式:

def myfunction():
    l = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
    total = 0
    for i in l:
        if total < 6:
            yield i  #yields an item and saves function state
            total += 1
        else:
            break

g = myfunction()

现在您可以通过调用 next() 访问 yield i 返回的所有元素:

>>> val = next(g)
>>> print(v)
a
>>> v = next(g)
>>> print(v)
b

或者,在 for 循环中执行以下操作:

>>> for returned_val in myfunction():
...    print(returned_val)
a
b
c
d
e
f

你想要的用列表切片最容易表达:

>>> l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
>>> l[:6]
# ['a', 'b', 'c', 'd', 'e', 'f']

或者创建另一个列表,您将在函数末尾return。

def myfunction():
    l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
    ret = []

    total = 0
    for i in l:
        if total < 6:
            total += 1
            ret.append(i)

    return ret

myfunction()

# ['a', 'b', 'c', 'd', 'e', 'f']

创建生成器的yield语句就是你想要的。

What does the "yield" keyword do in Python?

然后使用 next 方法获取循环返回的每个值。

var = my_func().next()