python数组作为参数列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4960689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python array as list of parameters
提问by bdfy
I have an array that matches the parameters of a function:
我有一个匹配函数参数的数组:
TmpfieldNames = []
TmpfieldNames.append(Trademark.name)
TmpfieldNames.append(Trademark.id)
return func(Trademark.name, Trademark.id)
func(Trademark.name.Trademark.id)works, but func(TmpfieldNames)doesn't. How can I call the function without explicitly indexing into the array like func(TmpfieldNames[0], TmpfieldNames[1])?
func(Trademark.name.Trademark.id)有效,但func(TmpfieldNames)无效。如何在不显式索引数组的情况下调用函数func(TmpfieldNames[0], TmpfieldNames[1])?
回答by etarion
I think what you are looking for is this:
我想你要找的是这个:
def f(a, b):
print a, b
arr = [1, 2]
f(*arr)
回答by Kevin Dolan
What you are looking for is:
您正在寻找的是:
func(*TmpfieldNames)
But this isn't the typical use case for such a feature; I'm assuming you've created it for demonstration.
但这不是此类功能的典型用例;我假设您已经创建它用于演示。
回答by Reiner Gerecke
With *you can unpack arguments from a listor tupleand **unpacks arguments from a dict.
随着*你打开行李从参数list或者tuple和**从解包参数dict。
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
Example from the documentation.
文档中的示例。

