【发布时间】: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