代码之家  ›  专栏  ›  技术社区  ›  froadie

如何分解一个元组,以便它可以作为参数列表传递?

  •  20
  • froadie  · 技术社区  · 15 年前

    假设我有一个这样的方法定义:

    def myMethod(a, b, c, d, e)
    

    然后,我有一个变量和一个这样的元组:

    myVariable = 1
    myTuple = (2, 3, 4, 5)
    

    有没有一种方法可以通过分解元组来传递其成员作为参数?类似这样(尽管我知道这不起作用,因为整个元组被视为第二个参数):

    myMethod(myVariable, myTuple)
    

    如果可能的话,我想避免单独引用每个元组成员…

    2 回复  |  直到 15 年前
        1
  •  37
  •   unutbu    15 年前

    你在找 argument unpacking 操作人员 * :

    myMethod(myVariable, *myTuple)
    
        2
  •  7
  •   Escualo    15 年前

    Python documentation :

    相反的情况发生在 参数已在列表中或 tuple,但需要为 需要分离的函数调用 位置参数。例如, 内置range()函数需要 分开开始和停止参数。如果 它们不能单独提供, 用编写函数调用 *-从列表或元组中解包参数的运算符:

    >>> 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]
    

    同样,字典也可以 使用传递关键字参数 **运算符:

    >>> def parrot(voltage, state='a stiff', action='voom'):
    ...     print "-- This parrot wouldn't", action,
    ...     print "if you put", voltage, "volts through it.",
    ...     print "E's", state, "!"
    ...
    >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
    >>> parrot(**d)
    -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
    
    推荐文章