【问题标题】:Python, tuple arguments playing nicely with othersPython,元组参数与其他参数配合得很好
【发布时间】:2026-02-01 16:35:01
【问题描述】:

例如:

mytuple = ("Hello","World")
def printstuff(one,two,three):
    print one,two,three

printstuff(mytuple," How are you")

这自然会因 TypeError 而崩溃,因为我只给它两个参数,而它需要三个参数。

有没有一种简单的方法可以有效地“拆分”元组而不是扩展所有内容?喜欢:

printstuff(mytuple[0],mytuple[1]," How are you")

【问题讨论】:

    标签: python arguments tuples typeerror


    【解决方案1】:

    有点,...你可以这样做:

    >>> def fun(a, b, c):
    ...     print(a, b, c)
    ...
    >>> fun(*(1, 2), 3)
      File "<stdin>", line 1
    SyntaxError: only named arguments may follow *expression
    >>> fun(*(1, 2), c=3)
    1 2 3
    

    如你所见,只要你用它的名字来限定后面的任何参数,你就可以做你想做的事。

    【讨论】:

      【解决方案2】:

      除非更改参数顺序或切换到命名参数。

      这是命名参数的替代方案。

      printstuff( *mytuple, three=" How are you" )
      

      这是切换顺序的替代方案。

      def printstuff( three, one, two ):
          print one, two, three
      
      printstuff( " How are you", *mytuple )
      

      这可能很糟糕。

      【讨论】:

        【解决方案3】:

        尝试以下方法:

        printstuff(*(mytuple[0:2]+(" how are you",)))
        

        【讨论】:

        • 匹配原始示例中的arity。
        • 但是mytuple 已经是一个二元组了。所以你没有明显的原因切片一个 2 元组(有效地复制它)。
        【解决方案4】:
        mytuple = ("Hello","World")
        
        def targs(tuple, *args):
            return tuple + args
        
        def printstuff(one,two,three):
            print one,two,three 
        
        printstuff(*targs(mytuple, " How are you"))
        Hello World  How are you
        

        【讨论】:

          【解决方案5】:

          你可以试试:

          def printstuff(*args):
              print args
          

          另一种选择是使用新的namedtuple 集合类型。

          【讨论】:

          • args 将是 (("hello","world)," how are you") 作为元组和字符串。
          【解决方案6】:

          实际上,可以在不改变参数顺序的情况下做到这一点。首先,您必须将字符串转换为元组,将其添加到元组 mytuple,然后将较大的元组作为参数传递。

          printstuff(*(mytuple+(" How are you",)))
          # With your example, it returns: "Hello World  How are you"
          

          【讨论】: