如何从列表中提取参数并将它们传递给函数调用 [英] How to extract parameters from a list and pass them to a function call
本文介绍了如何从列表中提取参数并将它们传递给函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从列表中提取项目并将它们作为参数传递给函数调用的好的、简短的方法是什么,例如在下面的示例中?
What is a good, brief way to extract items from a list and pass them as parameters to a function call, such as in the example below?
示例:
def add(a,b,c,d,e):
print(a,b,c,d,e)
x=(1,2,3,4,5)
add(magic_function(x))
推荐答案
您可以使用星号将元组或列表解包为位置参数.
You can unpack a tuple or a list into positional arguments using a star.
def add(a, b, c):
print(a, b, c)
x = (1, 2, 3)
add(*x)
同样,您可以使用双星将字典解包为关键字参数.
Similarly, you can use double star to unpack a dict into keyword arguments.
x = { 'a': 3, 'b': 1, 'c': 2 }
add(**x)
这篇关于如何从列表中提取参数并将它们传递给函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文