我已经发布了一个类似的问题,但我没有得到正确答案,可能是因为我不太清楚我希望程序运行的方式。
我正在写一个简单的礼物添加程序,我想向一个不同功能的词典中的人添加礼物。
def main():
print("Select: ")
print("\n\n\t1. Gifts")
selection_1 = input()
if selection_1 == "1":
people_list()
return selection
else:
print("Type a number for selecting.")
main()
def people_list():
people = {"Elena":["book","candy","sweater"],
"Daria":["healthy food"],
"Petra and Rok":[],
"Nikola":["cheese"],
"Matija + Elena":["vacation"],
"Christian":["chocolate"]}
print ("""Select a person to show their gifts:
1. Elena
2. Daria
3. Petra and Rok
4. Nikola
5. Matija + Elena
6. Christian
""")
gifts(people)
def gifts(people):
selection_2 = input()
if selection_2 == "1":
person = people["Elena"]
print(people["Elena"])
manage_gifts(person, people)
return person
elif selection_2 == "2":
person = people["Daria"]
print(people["Daria"])
manage_gifts(person, people)
return person
elif selection_2 == "3":
person = people["Petra and Rok"]
print(people["Petra and Rok"])
manage_gifts(person, people)
return person
elif selection_2 == "4":
person = people["Nikola"]
print(people["Nikola"])
manage_gifts(person, people)
return person
elif selection_2 == "5":
person = people["Matija + Elena"]
print(people["Matija + Elena"])
manage_gifts(person, people)
return person
elif selection_2 == "6":
person = people["Christian"]
print(people["Christian"])
manage_gifts(person, people)
return person
else:
print("Choose a person from the list!")
people_list()
return person
def manage_gifts(person, people):
print("""
1. Add gift""")
gift_option = input()
if gift_option == "1":
print("\nType the gift you would like to add?\n")
new_gift = input()
people[person].append(str(new_gift))
print("Gift added: ", people[person])
main()
我想要将新礼物添加到我从列表中选择的“人物”中。 我得到的错误是:
Traceback (most recent call last):
File "E:/Python/Vaje_Book/Gifts.py", line 92, in <module>
main()
File "E:/Python/Vaje_Book/Gifts.py", line 10, in main
people_list()
File "E:/Python/Vaje_Book/Gifts.py", line 36, in people_list
gifts(people)
File "E:/Python/Vaje_Book/Gifts.py", line 46, in gifts
manage_gifts(person, people)
File "E:/Python/Vaje_Book/Gifts.py", line 89, in manage_gifts
people[person].append(str(new_gift))
TypeError: unhashable type: 'list'
非常感谢你的帮助。
答案 0 :(得分:0)
gifts(people)
:
当您执行person = people["Elena"]
时,person
属于列表类型。
然后在manage_gifts(person, people)
:
当您执行people[person].append(str(new_gift))
时,错误TypeError: unhashable type: 'list'
会在逻辑上引发,因为person是一个列表。它应该是一个字符串。
我认为在gifts(people)
中,我应该用person = people["Elena"]
替换person = "Elena"
。等等person
变量的其他赋值。
然而,在此代码中还有其他错误需要解决:
- 请勿在{{1}}内拨打main()
- 不要在main()
答案 1 :(得分:0)
我没有足够的回复评论,但您应该知道在主要功能结束时调用main()
并不是好形式。 Python不进行尾调用优化,所以最终你会耗尽堆栈并以这种方式崩溃。把整个东西放在while循环中。 E.g。
def main():
while True:
print("Select: ")
print("\n\n\t1. Gifts")
selection_1 = input()
if selection_1 == "1":
people_list()
return selection
else:
print("Type a number for selecting.")