Python ValueError with Tuple being correct length

2024-04-20 04:45:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到以下错误:

Traceback (most recent call last):
  File "C:/Users/user/Documents/Data Munger/new_munger.py", line 49, in <module>
    for a, b in temp_tuple:
ValueError: too many values to unpack (expected 2)

从以下代码:

for key in d:
    for temp in d[key]:
        temp_tuple = (temp[0], [temp[i] for i in range(1, len(temp))])
        print(len(temp_tuple))
        e = defaultdict(list)
        for a, b in temp_tuple:
            e.setdefault(a, []).append(b)

print(len(temp_tuple))行在控制台中输出2。我不明白为什么会出现这个错误。你知道吗

谢谢你的帮助。你知道吗


Tags: keyinmostforlen错误callusers
2条回答

您的for循环已在temp_tuple上迭代。在第一个实例中,您试图将temp[0]解包到ab。可能你想做的是:

a, b = temp_tuple
e.setdefault(a, []).append(b)

虽然temp\ tuple的长度可能是2,但是for希望temp\ tuple中的每个项都是2个项(即长度为2个tuple的tuple)。你知道吗

相关问题 更多 >