Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

python - How to return values without breaking the loop?

I want to know how to return values without breaking a loop in Python.

Here is an example:

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

An example of using a generator:

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

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)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...