def foo(a, b, c):
print a+b+c
i = [1,2,3]
Is there a way to call foo(i) without explicit indexing on i? Trying to avoid foo(i[0], i[1], i[2])
有没有办法在没有显式索引的情况下调用foo(i)?试图避免foo(i [0],i [1],i [2])
3 个解决方案
#1
9
Yes, use foo(*i)
:
是的,使用foo(* i):
>>> foo(*i)
6
You can also use *
in function definition: def foo(*vargs)
puts all non-keyword arguments into a tuple called vargs
. and the use of **
, for eg., def foo(**kargs)
, will put all keyword arguments into a dictionary called kargs
:
您还可以在函数定义中使用*:def foo(* vargs)将所有非关键字参数放入名为vargs的元组中。并且使用**,例如,def foo(** kargs),将所有关键字参数放入名为kargs的字典中:
>>> def foo(*vargs, **kargs):
print vargs
print kargs
>>> foo(1, 2, 3, a="A", b="B")
(1, 2, 3)
{'a': 'A', 'b': 'B'}
#2
4
It's called argument unpacking and there's an operator for it.
它被称为参数解包,并且有一个运算符。
foo(*i)
By the way, it works with any iterable, not just with lists.
顺便说一句,它适用于任何可迭代的,而不仅仅是列表。
#3
3
Yes, Python supports that:
是的,Python支持:
foo(*i)
See the documentation on Unpacking Argument Lists. Works with anything iterable. With two stars **
it works for dicts and named arguments.
请参阅有关解压缩参数列表的文档。适用于任何可迭代的东西。有两颗星**它适用于dicts和命名参数。
def bar(a, b, c):
return a * b * c
j = {'a': 5, 'b': 3, 'c': 2}
bar(**j)
#1
9
Yes, use foo(*i)
:
是的,使用foo(* i):
>>> foo(*i)
6
You can also use *
in function definition: def foo(*vargs)
puts all non-keyword arguments into a tuple called vargs
. and the use of **
, for eg., def foo(**kargs)
, will put all keyword arguments into a dictionary called kargs
:
您还可以在函数定义中使用*:def foo(* vargs)将所有非关键字参数放入名为vargs的元组中。并且使用**,例如,def foo(** kargs),将所有关键字参数放入名为kargs的字典中:
>>> def foo(*vargs, **kargs):
print vargs
print kargs
>>> foo(1, 2, 3, a="A", b="B")
(1, 2, 3)
{'a': 'A', 'b': 'B'}
#2
4
It's called argument unpacking and there's an operator for it.
它被称为参数解包,并且有一个运算符。
foo(*i)
By the way, it works with any iterable, not just with lists.
顺便说一句,它适用于任何可迭代的,而不仅仅是列表。
#3
3
Yes, Python supports that:
是的,Python支持:
foo(*i)
See the documentation on Unpacking Argument Lists. Works with anything iterable. With two stars **
it works for dicts and named arguments.
请参阅有关解压缩参数列表的文档。适用于任何可迭代的东西。有两颗星**它适用于dicts和命名参数。
def bar(a, b, c):
return a * b * c
j = {'a': 5, 'b': 3, 'c': 2}
bar(**j)