เหตุใดการโต้แย้ง tuple จากพจนานุกรมจึงมีเครื่องหมายจุลภาคต่อท้าย

เมื่อเร็ว ๆ นี้ฉันสังเกตเห็นว่าเมื่อฉันส่งผ่านไปยังอาร์กิวเมนต์ของฟังก์ชันซึ่งเป็นค่าทูเพิลจากพจนานุกรม มันมีเครื่องหมายจุลภาคต่อท้ายที่ส่วนท้าย ร้องเป็นตัวอย่างโค้ดอย่างง่ายของปัญหาของฉัน

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)

ฉันสงสัยว่าทำไมล่ามหลามจึงตัดสินใจแพ็คทูเพิลจากพจนานุกรมแบบนี้ ฉันใช้ python3.6


person zviad    schedule 10.05.2018    source แหล่งที่มา


คำตอบ (1)


คุณส่งผ่าน tuple เป็นอาร์กิวเมนต์แรก คุณต้องแตกค่า:

myfun(*arg_dict[0])
person Konstantin    schedule 10.05.2018