【发布时间】:2022-10-08 23:13:23
【问题描述】:
这是我的代码,它是一个简单的动物分类程序。
horse = {
"name": "Horse",
"legs": 4,
"land": "yes",
"pet": "yes",
"stripe": "no"
}
dolphin = {
"name": "Dolphin",
"legs": 0,
"land": "no",
"pet": "no",
"stripe": "no"
}
userIn = dict()
userIn["legs"] = int(input("How many legs does it have? "))
userIn["land"] = input("Is it a land animal (yes/no)? ")
userIn["pet"] = input("Is it a pet? ")
userIn["stripe"] = input("Does it have stripes? ")
animals = [horse, dolphin]
for animal in animals:
bak = animal
bak.pop("name")
print(bak)
print(animal)
if bak == userIn:
print(animal["name"])
但是,在我说bak.pop("name") 的最后,它也会从animal 中删除"name"。
如何让它从bak 中删除"name" 而不是animal?
【问题讨论】:
-
当您执行
bak = animal时,您不会复制。您只需为附加名称animal的对象提供附加名称bak。 -
这回答了你的问题了吗? How to copy a dictionary and only edit the copy
-
@Matthias 感谢您的快速回答!有没有办法复制一个对象,然后将它分配给一个变量?
标签: python