"返回"在函数中只返回一个值 [英] "Return" in Function only Returning one Value

查看:163
本文介绍了"返回"在函数中只返回一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  x = 4 $ b $我们说我写了一个for循环来输出所有的数字1到x: b为xrange(1,x + 1)中的数字:
打印号,
#输出:
1
2
3
4

现在,把这个循环放到一个函数中:

  def counter(x):
用于xrange(1,x + 1)中的数字:
返回数字
打印计数器(4)
$输出:
1

为什么我只有取得一个值for循环到一个函数?

我已经通过将for循环的所有结果附加到一个列表,然后返回列表来回避这个问题。 p>

为什么for循环会追加所有结果,而不仅仅是一个?:

 <$ c (x,1):
output.append(number)
返回输出$ b $ def $($)
output = []
b $ b

什么是最好的方法返回所有值,附加到列表似乎效率非常低。

解决方案

return 就像关键字的名字所暗示的一样。当你按下这条语句时,它会返回,而其余的函数不会被执行。

您可能想要的是 yield 关键字。这将创建一个生成器函数(一个返回生成器的函数)。发生器是可迭代的。每次执行 yield 表达式时,它们都会产生一个元素。

  def func():
在范围内(10):
产生x

发生器= func()
产生器中的元素:
打印项目


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.

解决方案

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

这篇关于&QUOT;返回&QUOT;在函数中只返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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