是否有语法允许您将列表扩展到函数调用的参数中?
示例:
# Trivial example function, not meant to do anything useful.
def foo(x,y,z):
return "%d, %d, %d" %(x,y,z)
# List of values that I want to pass into foo.
values = [1,2,3]
# I want to do something like this, and get the result "1, 2, 3":
foo( values.howDoYouExpandMe() )
发布于 2011-10-13 04:13:10
它是存在的,但很难搜索。我想大多数人把它叫做"splat“运算符。
它在文档中被命名为"Unpacking argument lists“。
你可以这样使用它:foo(*values)
。还有一个用于字典的:
d = {'a': 1, 'b': 2}
def foo(a, b):
pass
foo(**d)
发布于 2011-10-13 04:18:34
您应该使用*运算符,就像foo(*values)
读取Python文档unpackaging argument lists一样。
另外,一定要阅读以下内容:http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
def foo(x,y,z):
return "%d, %d, %d" % (x,y,z)
values = [1,2,3]
# the solution.
foo(*values)
发布于 2011-10-13 04:13:07
https://stackoverflow.com/questions/7745952
复制相似问题