【问题标题】:Why passed tuple argument from dictionary has trailing comma?为什么从字典传递的元组参数有尾随逗号?
【发布时间】:2018-05-10 19:23:29
【问题描述】:

最近我注意到,当我将字典中的元组值传递给函数参数时,它的末尾有逗号。 Bellow 是我的问题的简单代码示例。

def myfun(*args):
   print(f'args={args}')
   x, y = args
   print(f'x={x}, y={y}')


myfun(1, 2) # passing arguments this way works fine
arg_dict = {0: (1, 2), 1: (2, 3)}
print(f'arg_dict[0]={arg_dict[0]}') # when I print dictionary value it seems quite OK.
myfun(arg_dict[0]) # passed dictionary value has trailing comma.

这是输出:

args=(1, 2)
x=1, y=2
arg_dict[0]=(1, 2)
args=((1, 2),)
Traceback (most recent call last):
  File "c:\Users\name\Documents\pname\test.py", line 28, in <module>
    myfun(arg_dict[0])
  File "c:\Users\name\Documents\pname\test.py", line 21, in myfun
    x, y = args
ValueError: not enough values to unpack (expected 2, got 1)

我想知道为什么 python 解释器决定像这样从字典中打包元组? 我正在使用 python3.6。

【问题讨论】:

    标签: python python-3.x python-3.6


    【解决方案1】:

    您将元组作为第一个参数传递。 你需要解压值:

    myfun(*arg_dict[0])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 2021-11-20
      • 1970-01-01
      • 2011-04-14
      相关资源
      最近更新 更多