【问题标题】:How to stop dict.pop("foo") from deleting every dict item with name the "foo"?如何阻止 dict.pop(\"foo\") 删除每个名为 \"foo\" 的 dict 项目?
【发布时间】: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


【解决方案1】:

尝试这个;

for animal in animals:
    bak = animal.copy() #edit here
    bak.pop("name")
    print(bak)
    print(animal)
    if bak == userIn:
        print(animal["name"])

【讨论】:

    【解决方案2】:

    使用 deepcopy 而不是 bak = animal

    import copy
    
    for animal in animals:
        bak = copy.deepcopy(animal)
        print(bak)
        print(animal)
        if bak == userIn:
            print(animal["name"])
    

    【讨论】:

      猜你喜欢
      • 2021-06-02
      • 1970-01-01
      • 1970-01-01
      • 2016-02-04
      • 1970-01-01
      • 2013-01-30
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多