简体   繁体   English

以简单的方式将多个参数从数组传递到函数

[英]Passing several arguments from an array to a function in a easy way

Well I really don't know how to describe this in words but I've an easy example: 好吧,我真的不知道如何用语言来描述,但是我有一个简单的例子:

def foo(x,y,z):
     r=x+....

a = [1,2,3]
foo(a[0], a[1], a[2])

Can I do the same without calling a[n] several times? 我可以不打几次a[n]而做同样的事情吗? but keeping "x,y,z" definition? 但是保留“ x,y,z”的定义?

Use the unpacking operator ! 使用开箱操作员

>>> def foo(x,y,z):
...     return x+y+z
... 
>>> a = [1,2,3]
>>> foo(*a)
6

From the documentation 从文档中

If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple: 如果不能单独使用它们,请使用* -operator编写函数调用,以将参数从列表或元组中解包:

 >>> args = [3, 6] >>> range(*args) # call with arguments unpacked from a list [3, 4, 5] 

Yeah use unpacking operator to pass any arbitrary arguments to your function : 是的,请使用拆包运算符将任意参数传递给您的函数:

def foo(*args):
     for i in args : # you can iterate over args or get its elements by indexing
         #do stuff

a = [1,2,3]
foo(*a)

And if you just pass 3 argument you can use unpacking in call time. 而且,如果您仅传递3个参数,则可以在通话时间中使用拆包功能。

def foo(x,y,z):
     r=x+....

a = [1,2,3]
foo(*a)

Try this 尝试这个

def foo(x,y,z):
     r=x+....

a = [1,2,3]
foo(*a)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM