【问题标题】:How to expand a list to function arguments in Python [duplicate]如何在Python中将列表扩展为函数参数[重复]
【发布时间】:2011-12-06 10:52:43
【问题描述】:

是否有语法允许您将列表扩展为函数调用的参数?

例子:

# 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() )

【问题讨论】:

  • 为什么不给函数一个元组?
  • @lc2817 我正在使用无法更改的库函数,并且作为参数传入的数据已经在数组中。
  • 我反对将其标记为重复的决定。链接到*args 的解释是正确的,但声称这个问题重复是在要求人们玩 Jeopardy。只有知道这个问题的答案(即“使用 *args”),才能知道要搜索声称是重复的问题。

标签: python arguments


【解决方案1】:

它存在,但很难搜索。我想大多数人都称它为“splat”运算符。

它在文档中为“Unpacking argument lists”。

您可以这样使用它:foo(*values)。还有一个用于字典:

d = {'a': 1, 'b': 2}
def foo(a, b):
    pass
foo(**d)

【讨论】:

    【解决方案2】:

    您应该使用 * 运算符,例如 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)
    

    【讨论】:

      【解决方案3】:

      尝试以下方法:

      foo(*values)
      

      这可以在 Python 文档中找到 Unpacking Argument Lists

      【讨论】:

        【解决方案4】:

        这可以通过:

        foo(*values)
        

        【讨论】:

          猜你喜欢
          • 2019-09-23
          • 2015-10-07
          • 1970-01-01
          • 2015-06-06
          • 2011-03-31
          • 2018-08-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多