Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
571 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...