如何在不中断循环的情况下返回值? [英] How to return values without breaking the loop?

查看:121
本文介绍了如何在不中断循环的情况下返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在不破坏Python循环的情况下返回值.

I want to know how to return values without breaking a loop in 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 will only get the first answer then leave the loop, I don't want that, I want to return multiple elements till the end of that loop.

如何解决这个问题,有什么解决办法吗?

How can resolve this, is there any solution?

推荐答案

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

You can create a generator for that, so you could yield values from your generator (your function would become a generator after using the yield statement).

请参阅以下主题,以更好地了解如何使用它:

See the topics below to get a better idea of how to work with it:

  • Generators
  • What does the "yield" keyword do in Python?
  • yield and Generators explain's

使用生成器的示例:

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项目添加到该列表,然后返回该列表,因此可以将该列表视为循环内返回"的结果列表.

Also you could create a list before the loop starts and append items to that list, then return that list, so this list could be treated as list of results "returned" inside the loop.

使用列表返回值的示例:

Example of using list to return values:

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列表中返回多少个值,以避免too many values to unpack错误

NOTE: In the approach with list you have to know how many values your function would return in results list to avoid too many values to unpack error

这篇关于如何在不中断循环的情况下返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆