如何在 Python 中将列表作为函数的输入传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35120620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass a list as an input of a function in Python
提问by Arpan Das
I am using Python, and I have a function which takes a list as the argument. For example, I am using the following syntax,
我正在使用 Python,并且我有一个将列表作为参数的函数。例如,我使用以下语法,
def square(x,result= []):
for y in x:
result.append=math.pow(y,2.0)
return result
print(square([1,2,3]))
and the output is [1]
only where I am supposed to get [1,4,9]
.
并且输出[1]
只是我应该得到的地方[1,4,9]
。
What am I doing wrong?
我究竟做错了什么?
采纳答案by gtlambert
You are currently returning a value from your function in the first iteration of your for
loop. Because of this, the second and third iteration of your for
loop never take place. You need to move your return
statement outside of the loop as follows:
您当前正在for
循环的第一次迭代中从您的函数返回一个值。因此,for
循环的第二次和第三次迭代永远不会发生。您需要将return
语句移到循环之外,如下所示:
import math
def square(x):
result = []
for y in x:
result.append(math.pow(y,2.0))
return result
print(square([1,2,3]))
Output
输出
[1.0, 4.0, 9.0]
回答by Hugh Bothwell
Why not side-step the problem altogether?
为什么不完全回避问题呢?
def square(vals):
return [v*v for v in vals]
Edit:The first problem, as several people have pointed out, is that you are short-circuiting your for
loop. Your return
should come afterthe loop, not in it.
编辑:第一个问题,正如一些人所指出的,是你正在短路你的for
循环。你return
应该在循环之后,而不是在循环中。
The next problem is your use of list.append
- you need to call it, not assign to it, ie result.append(y*y)
. result.append = y*y
instead overwrites the method with a numeric value, probably throwing an error the next time you try to call it.
下一个问题是您的使用list.append
- 您需要调用它,而不是分配给它,即result.append(y*y)
. result.append = y*y
而是用数值覆盖该方法,可能会在您下次尝试调用它时抛出错误。
Once you fix that, you will find another less obvious error occurs if you call your function repeatedly:
一旦你解决了这个问题,如果你重复调用你的函数,你会发现另一个不太明显的错误发生:
print(square([1,2,3]) # => [1, 4, 9]
print(square([1,2,3]) # => [1, 4, 9, 1, 4, 9]
Because you pass a mutable item (a list) as a default, all further use of that default item points back to the same original list.
因为您将可变项(列表)作为默认值传递,所以对该默认项的所有进一步使用都指向同一个原始列表。
Instead, try
相反,尝试
def square(vals, result=None):
if result is None:
result = []
result.extend(v*v for v in vals)
return result
回答by Munir
You should return outside the for loop. Otherwise, it will stop after first iteration.
您应该在 for 循环之外返回。否则,它将在第一次迭代后停止。
def square(x):
result=[]
for y in x:
result.append(math.pow(y,2.0)) # add to list after calculation
return result
print(square([1,2,3])
回答by Alexander
We even use result
? You can use a list comprehension to generate your result which you then return. I'm not sure why you passed result
as a variable into the function, since it is not used.
我们甚至使用result
? 您可以使用列表理解来生成结果,然后返回该结果。我不确定您为什么result
将变量作为变量传递给函数,因为它没有被使用。
Also, having return result
inside your loop means the function returns the value on the first iteration, so it just returns the square of the first number in the list.
此外,return result
在循环中意味着该函数在第一次迭代时返回值,因此它只返回列表中第一个数字的平方。
import math
def square(x):
return [math.pow(y, 2) for y in x]
>>> print(square([1,2,3]))
[1.0, 4.0, 9.0]
回答by user2255757
your code doesn't make sense anywhere. syntax error at the end missing the closing bracket for the print, return call inside the for loop meaning it only executes once, and result.append is a function not a constructor sp the correct call is
你的代码在任何地方都没有意义。最后的语法错误缺少打印的右括号,for 循环内的 return 调用意味着它只执行一次,并且 result.append 是一个函数而不是构造函数 sp 正确的调用是
result.append(math.pow(y,2))
the only thing that is not an issue is the passing of the list which is your question, the function is receiving the whole list if you do
唯一不是问题的是传递列表,这是您的问题,如果您这样做,该函数将接收整个列表
def f(a):
print a
f([1,2,3])
out
出去
[1,2,3,]
回答by Tobias Kienzler
You might be interested in using yield
您可能有兴趣使用 yield
def square(x):
for y in x:
yield math.pow(y, 2.0)
that way you can either call
这样你就可以打电话
for sq in square(x):
...
which won't generate the entire list of squares at once but rather one element per iteration, or use list(square(x))
to obtain the full list on demand.
它不会一次生成整个方块列表,而是每次迭代生成一个元素,或者用于list(square(x))
按需获取完整列表。
回答by richardlaborde
This is a fun opportunity to use a slightly more functional style:
这是使用稍微更实用的样式的有趣机会:
import math
map(lambda x:(math.pow(x,2)), [1,2,3])
This uses the map
function, which takes a list and a function, and returns a new list where that function has been applied individually to each member of the list. In this case, it applies the math.pow(x,2)
function to each member of the list, where each number is x.
这使用了map
函数,它接受一个列表和一个函数,并返回一个新列表,其中该函数已单独应用于列表的每个成员。在这种情况下,它将math.pow(x,2)
函数应用于列表的每个成员,其中每个数字都是 x。
Notice that map(lambda x:(math.pow(x,2)), [1,2,3])
returns an iterable, which is really convenient, but if you need to get a list back just wrap the entire statement in list()
.
请注意,map(lambda x:(math.pow(x,2)), [1,2,3])
返回一个可迭代对象,这确实很方便,但是如果您需要返回一个列表,只需将整个语句包装在list()
.