python - 将 n 个参数传递给 Python 中的函数

标签 python arguments

我有一个函数,它接受可变数量的变量作为参数。我如何将下面示例中 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 是一个元组。 *argsarg 转换为参数列表。您定义 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/

相关文章:

python - 将按 df 分组转换为带有字典列表的字典

Python __imul__() 方法

php - 开发一致库的最佳实践是什么?

django - 将附加参数传递给 django 登录名和模板

c# - 在 C# 中使用可变数量的参数调用 GetStoredProcCommand?

java - 使用 List<> 参数重载 Java 函数

python - 如何使在函数内创建的变量成为全局变量?

python - 不明白这个SyntaxError : illegal target for annotation

python - 压缩和应用函数列表和相应参数时出现类型错误

c++ - CreateprocessW 截断的命令行参数