每当我运行这段代码时,python就会给我:
ValueError:没有足够的值可解压缩(预期3,得到2)
我正在尝试制作一种通讯录,您可以在其中添加,删除和更改信息。我试图更改第20行中存在for
-in
循环的代码(该行实际上是问题的根源),但是没有给出任何结果。
members = {}
class Member:
def __init__(self, name, email, number):
self.name = name
self.email = email
self.number = number
def addmember(name, email, number):
members[name] = email, number
print('Member {0} has been added to addressbook'.format(name))
def Check():
print("You've got {0} members in your addressbook".format(len(members)))
for name, email, number in members.items(): #the problem is here
print('Contact {0} has email:{1} and has number:{2}'.format(name, email, number))
print('')
Member.addmember('Tim', 'email@mail.com', '43454')
Member.Check()
答案 0 :(得分:5)
该错误几乎可以告诉您发生了什么:您正试图从列表中解压缩3个项目,但是members.items()
返回的是dict_items
类键值对,每个键值对看起来像
('Tim', ['email@mail.com', '43454'])
您可以使用
name, info in members.items()
其中info
是(email, number)
或
name, (email, number) in members.items()
将值元组直接解压缩为两个不同的变量。