问题
Let's say I write a for loop that will output all the numbers 1 to x:
x=4
for number in xrange(1,x+1):
print number,
#Output:
1
2
3
4
Now, putting that same for loop into a function:
def counter(x):
for number in xrange(1,x+1):
return number
print counter(4)
#Output:
1
Why do I only obtain one value when I put the for-loop into a function?
I have been evading this problem by appending all the results of the for-loop to a list, and then returning the list.
Why does the for loop append all the results, and not just one?:
def counter(x):
output=[]
for number in xrange(1,x+1):
output.append(number)
return output
What is the best method of returning all the values, appending to a list seems very inefficient.
回答1:
return
does exactly like the keyword's name implies. When you hit that statement, it returns and the rest of the function is not executed.
What you might want instead is the yield
keyword. This will create a generator function (a function that returns a generator). Generators are iterable. They "yield" one element each time the yield
expression is executed.
def func():
for x in range(10):
yield x
generator = func()
for item in generator:
print item
回答2:
What you want is is called a Generator:
def counter(x):
for number in xrange(1,x+1):
yield number
You would then use it like this:
c = counter(5)
next(c) # 1
next(c) # 2
You could also consume the entire generator by doing:
xs = list(c) # xs = [1, 2, 3, 4, 5]
See: http://docs.python.org/2/tutorial/classes.html#generators for more information.
The return statement in Python returns form the function and does not save any state. Every time you call the function a new stack frame is created. yield on the other hand is (more or less) Python's equivilent of continutations
回答3:
Once return
in a function, the function ends and the remaining code won't be excuted any more.
Your second solution is good and if you want better solution, you can use generator:
def counter(x):
for number in xrange(1,x+1):
yield number
And then you can use it like this:
>>> for i in counter(5):
... print i
...
1
2
3
4
5
来源:https://stackoverflow.com/questions/20604773/return-in-function-only-returning-one-value