我有一个函数,它接受可变数量的变量作为参数。我如何将下面示例中 some_list
的内容添加到我的 myfunc2()
def myfunc1(*args):
arguments = [i for i in args]
#doing some processing with arguments...
some_list = [1,2,3,4,5] # length of list depends on what was passed as *args
var = myfunc2(???)
我能想到的唯一方法是将列表或元组作为参数传递给 myfunc2()
,但也许有更优雅的解决方案,因此我不必重写 myfunc2()
和其他几个函数。
最佳答案
args
是一个元组。 *args
将 arg
转换为参数列表。您定义 myfunc2
的方式与 myfunc1
相同:
def myfunc2(*args):
pass
要传递参数,您可以一个一个地传递:
myfunc2(a, b, c)
*
运算符的石斑鱼:
newargs = (a, b, c)
myfunc2(*newargs)
或结合使用这两种技术:
newargs = (b, c)
myfunc2(a, *newargs)
这同样适用于 **
运算符,它将 dict 转换为命名参数列表。
关于python - 将 n 个参数传递给 Python 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15953185/