【问题标题】:Error: ValueError: too many values to unpack (expected 3)错误:ValueError:要解包的值太多(预期为 3)
【发布时间】:2020-01-29 11:21:36
【问题描述】:

在迭代元组时出现以下错误。我不确定我需要应用哪些更改来进行迭代。任何帮助将不胜感激。

ValueError:解包的值太多(预计为 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 (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,以检查发生了什么?
  • @JammyDodger 在 if 条件下添加了打印语句,您可以在回溯底部看到打印的消息。
  • 在元组 (777, '5000435011607', '00720645') 你真的需要 '777' 吗?
  • @t_e_o 我已经添加了预期的结果。
  • 这种for循环是从哪里学来的? for x,y,z in list? @Tester

标签: python


【解决方案1】:
       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-tuple 的情况下也犯了同样的错误。

你的 sn-p 中还有一些其他值得商榷的地方:

  • 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`
    

    你也不需要所有的检查,使用 slice 来追加所有的值

    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)
    

    【讨论】:

      【解决方案3】:

      如果您的元组格式为 [(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
              '''
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-27
        • 1970-01-01
        • 2014-07-31
        • 2020-02-24
        • 2019-04-19
        • 1970-01-01
        相关资源
        最近更新 更多