问题描述
我正在编写一个小脚本,我在其中调用 itertools.product,如下所示:
I am writing a little script in which I call itertools.product like so:
for p in product(list1,list2,list3):
self.createFile(p)
有没有办法让我在不事先知道要包含多少个列表的情况下调用这个函数?
Is there a way for me to call this function without knowing in advance how many lists to include?
谢谢
推荐答案
您可以使用星号或 splat 运算符(它有几个名称): for p in product(*lists)
where lists
是一个元组或你想要传递的东西的列表.
You can use the star or splat operator (it has a few names): for p in product(*lists)
where lists
is a tuple or list of things you want to pass.
def func(a,b):
print (a,b)
args=(1,2)
func(*args)
您可以在定义函数时做类似的事情以允许它接受可变数量的参数:
You can do a similar thing when defining a function to allow it to accept a variable number of arguments:
def func2(*args): #unpacking
print(args) #args is a tuple
func2(1,2) #prints (1, 2)
当然,您可以将 splat 运算符与可变数量的参数结合使用:
And of course, you can combine the splat operator with the variable number of arguments:
args = (1,2,3)
func2(*args) #prints (1, 2, 3)
这篇关于使用未知数量的参数调用python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!