Python ValueError:解包的值太多 [英] Python ValueError: too many values to unpack

查看:79
本文介绍了Python ValueError:解包的值太多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从这段代码中得到了这个异常:

I am getting that exception from this code:

class Transaction:
    def __init__ (self):
        self.materials = {}

    def add_material (self, m):
        self.materials[m.type + m.purity] = m

    def serialize (self):
        ser_str = 'transaction_start\n'

        for k, m in self.materials:
            ser_str += m.serialize ()

        sert += 'transaction_end\n'
        return ser_str

for 行是抛出异常的那一行.mMaterial 对象.有人知道为什么吗?

The for line is the one throwing the exception. The ms are Material objects. Anybody have any ideas why?

推荐答案

self.materials 是一个 dict 并且默认情况下您只迭代键(它们是字符串).

self.materials is a dict and by default you are iterating over just the keys (which are strings).

因为 self.materials 有两个以上的键*,它们无法解压到tuple "k, m",因此 ValueError 异常.

Since self.materials has more than two keys*, they can't be unpacked into the tuple "k, m", hence the ValueError exception is raised.

在 Python 2.x 中,迭代键和值(tuple "k, m"),我们使用 self.materials.iteritems().

In Python 2.x, to iterate over the keys and the values (the tuple "k, m"), we use self.materials.iteritems().

然而,既然你无论如何都要把键扔掉,你也可以简单地迭代字典的值:

However, since you're throwing the key away anyway, you may as well simply iterate over the dictionary's values:

for m in self.materials.itervalues():

在 Python 3.x 中,更喜欢 dict.values()(返回一个 字典视图对象):

In Python 3.x, prefer dict.values() (which returns a dictionary view object):

for m in self.materials.values():

这篇关于Python ValueError:解包的值太多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆