Passing a list of parameters into a Python function
本问题已经有最佳答案,请猛点这里访问。
如何将未知数量的参数传递给函数?我的函数定义如下
1 2 | def func(x, *p): return ... |
我正试图传递一个用作参数的值列表。我尝试使用列表和元组,但函数总是返回零。有人有什么建议吗?谢谢
1 2 | some_list = ["some","values","in","a","list", ] func(*some_list) |
这相当于:
1 | func("some","values","in","a","list") |
固定的
1 | func(5, *some_list) |
…相当于:
1 | func(5,"some","values","in","a","list") |
如果您没有为
将值作为逗号分隔的值传递
1 2 3 4 5 6 7 8 9 10 11 12 | >>> def func(x, *p): # p is stored as tuple ... print"x =",x ... for i in p: ... print i ... return p ... >>> print func(1,2,3,4) # x value 1, p takes the rest x = 1 2 3 4 (2,3,4) # returns p as a tuple |
您可以通过阅读文档了解更多信息