【问题标题】:Why does a comma appear in the output after the string is used in unpacking in a function?为什么在函数中使用字符串解包后输出中会出现逗号?
【发布时间】:2019-12-17 15:41:47
【问题描述】:
def func(*n):
    print(n)

func(1,2,3,4)
func(*(1,2,3))
func((1,2,3,'hey'))
func(('hey',1))
output:
(1, 2, 3, 4)
(1, 2, 3)
((1, 2, 3, 'hey'),)
(('hey', 1),)

将字符串添加到参数时,元组后面会出现逗号。

【问题讨论】:

    标签: python python-3.x parameter-passing variadic-functions


    【解决方案1】:

    您在后面看到, 的原因是因为() 是一个函数调用,而(some_object,) 是一个元组。

    >>> tuple()
    ()
    >>> tuple([None])
    (None,)
    

    当您传递最后两个函数调用的参数时,请注意双精度 (())

    func((1,2,3,'hey'))
    func(('hey',1))
    

    所以你传递的是最后两个的元组。查看每个的类型

    >>> type(('test'))
    <class 'str'>
    >>> type(('test', 1))
    <class 'tuple'>
    

    如果您不想要尾随逗号,请删除 args 周围多余的 ()

    【讨论】:

      【解决方案2】:

      这种行为是意料之中的:您传递给底部两个示例中的函数的元组代表可变参数 *args 元组中的第一个参数(名称无关紧要,您使用的是 *n)。 *args 的目的是创建一个元组,其中包含传递给函数的所有非关键字参数。

      创建单个元素的元组总是打印尾随逗号以将其区分为元组。在下面两种情况下,您有一个单元素 args 元组,其中一个 4 或 2 个元素的元组作为其唯一元素。

      您的句子“将字符串添加到参数时,元组后出现逗号”不正确-您从调用中删除了解包运算符*,该调用不再将元组扁平化为可变参数,因此字符串无关用它。即使您将数字作为唯一参数传递,您仍然会得到悬挂的逗号:

      >>> def f(*args): print(args)
      ...
      >>> f(1)
      (1,)          # `args` tuple contains one number
      >>> f(1, 2)
      (1, 2)        # `args` tuple contains two numbers
      >>> f((1, 2))
      ((1, 2),)     # two-element tuple `(1, 2)` inside single-element `args` tuple
      >>> f((1,))
      ((1,),)       # single-element tuple `(1,)` inside single-element `args` tuple
      >>> f(*(1,))  # unpack the tuple in the caller, same as `f(1)`
      (1,) 
      >>> f(*(1,2)) # as above but with 2 elements
      (1, 2) 
      >>> f((1))    # without the trailing comma, `(1)` resolves to `1` and is not a tuple
      (1,)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-26
        • 1970-01-01
        • 1970-01-01
        • 2012-03-27
        • 1970-01-01
        相关资源
        最近更新 更多