错误:ValueError: 值过多,应该期望3个。

3

在迭代元组时出现以下错误。我不确定需要做什么更改才能进行迭代。任何帮助将不胜感激。

ValueError: too many values to unpack (expected 3)

程序:

 def convert_tuple_to_dict(self, tup):

        dt = defaultdict(list)
        temp_lst = []

        for i in range(len(tup)):

            if (len(tup[i]) == 2):
                for a, b in tup:
                    dt[a].append(b)

            if (len(tup[i]) == 3):
                print(tup[i])
                for (a, b, c) in tup[i]:
                    dt[a].append(b)
                    dt[a].append(c)

        return dict(dt)

    run = DataType()
    print(run.convert_tuple_to_dict(
        (('1328', '50434022', '53327'), (777, '5000435011607', '00720645'))))

Traceback详情:

Traceback (most recent call last):
  File "foo/DataType.py", line 95, in <module>
    print(run.convert_tuple_to_dict(
  File "foo/DataType.py", line 86, in convert_tuple_to_dict
    for (a, b, c) in tup[i]:
ValueError: too many values to unpack (expected 3)
('1328', '50434022', '53327')

期望输出:

{'1328': ['50434022', '53327'], 777: ['5000435011607', '00720645']}

你能在循环的每次迭代中打印出tup,以便检查发生了什么吗? - clubby789
@JammyDodger 在条件语句下面添加了打印语句,你可以在回溯信息的底部看到打印出来的消息。 - Learner
在元组(777,'5000435011607','00720645')中,您实际上需要的是“777”吗? - teoML
@t_e_o 我已经添加了预期结果。 - Learner
1
你是从哪里学到这种 for x,y,z in list 的循环的?@Tester - taurus05
如果您确定列表中每个元素只有3个值,那么这是完全可以接受的。 - Jean-François Fabre
3个回答

4
       if (len(tup[i]) == 3):
            print(tup[i])
            for (a, b, c) in tup[i]:

在这里,您正在检查tup[i]的长度,然后对其进行迭代并尝试进一步拆包每个项目。

因此,考虑到tup[i] =('1328','50434022','53327'),您将执行以下操作:

a, b, c = '1328'
a, b, c = '50434022'
a, b, c = '53327'

这可能不是你尝试做的事情。解决方案是不迭代元组,直接拆包赋值...
a, b, c = tup[i]
# do the thing

恰巧在2元组案例中也存在同样的错误。

您的代码还有一些争议点:

  • tup并不是一个元组,它是一系列输入的序列,因此命名是具有误导性的。
  • 您在range(len(...))上迭代时没有必要使用索引,只需直接迭代即可。
  • 您可以使用扩展拆包来完全不关心输入元组的长度:
def convert_tuple_to_dict(self, in_tuples):
    dt = defaultdict(list)
    for key, *values in in_tuples:
        dt[key].extend(values)
    return dict(dt)

2
解压缩操作不应该在循环中进行。
if len(tup[i]) == 3:
    a, b, c = tup[i]
    dt[a].append(b)
    dt[a].append(c)

for x in tup[i] 已经对元组进行了解包,这意味着您正在尝试将一个值分配给3个变量。

a, b, c = `1328`

你不需要进行所有检查,使用切片将所有值追加。
def convert_tuple_to_dict(self, tup):

    dt = defaultdict(list)

    for i in range(len(tup)):
        dt[tup[i][0]].extend(tup[i][1:])

    return dict(dt)

1
如果你的元组格式为[(x1,y1,z1),(x2,y2,z2),(x3,y3,z3), ... ,(xn,yn,zn)],你可以这样做:
for x,y,z in my_tuple:
        '''
        Rest of the code goes here -- it can loop over each element of the list of tuples
        And unpack each element of the tuple in the form of x,y,z
        '''

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接