【问题标题】:dictionaries with different names and how to print the name具有不同名称的字典以及如何打印名称
【发布时间】:2021-10-28 01:23:14
【问题描述】:

宠物:制作几个字典,其中每个字典的名称是 宠物的名字。在每本字典中,包括动物的种类和主人的名字 姓名。将这些字典存储在一个名为 pets 的列表中。接下来,遍历您的列表 当您打印出您所知道的关于每只宠物的所有信息时。

您好,我有这个问题。我已经完成了解决方案,但我想打印字典名称而不为每个都写打印

解决方案:

jumbo = {"kind":"cat",
         "owner":"Rahma",
}
 


snoopy = {"kind":"dog",
          "owner":"fahad",
}


shilla = {"kind":"bird",
          "owner":"farooq",
}


pets = [jumbo,snoopy,shilla] # created list 

#loop through your list and as you do print everything you know about each pet

for pet in pets :
    print ( "jumbo" + " is "+ pet["kind"] + " the owner is " + pet["owner"].title() + "." ) )

问题是我正在尝试使用创建的宠物列表打印每个循环中的名称

【问题讨论】:

  • 您能否重新表述您的问题?
  • 在宠物字典中包含宠物的名字,作为额外的字段:jumbo = { 'name': 'jumbo', "kind":"cat", "owner":"Rahma" }
  • 我从书中得到了这个问题,所以我无法重新表述它#Petr L
  • jumbo = { 'name': 'jumbo', "kind":"cat", "owner":"Rahma" } 这将完美运行。但是还有另一种方法吗?我正在学习这就是为什么我要问 -stef

标签: python list dictionary for-loop


【解决方案1】:

你可以像下面这样使用eval()(见ref):

jumbo = {"kind":"cat",
         "owner":"Rahma",
}

snoopy = {"kind":"dog",
          "owner":"fahad",
}

shilla = {"kind":"bird",
          "owner":"farooq",
}

pets = ['jumbo','snoopy','shilla'] # created list 

for pet in pets :
    print ( (pet) + " is "+ str(eval(pet)["kind"]) + " the owner is " + str(eval(pet)["owner"]) + "." )

输出:

jumbo is cat the owner is Rahma.
snoopy is dog the owner is fahad.
shilla is bird the owner is farooq.

【讨论】:

  • 我不会在任何严肃的程序中推荐这种方法。变量名和宠物名不能相互依赖。这就是我们最终得到意大利面条代码的方式。
  • @lachi007,欢迎,请不要忘记accept 回答和upvote
  • 您好,谢谢您的提醒。我会这样做的。
【解决方案2】:

试试这两种解决方案:

首先 - 带有宠物名称列表的 Zip:

names = ["jumbo", "snoopy", "shilla"]

# loop through your list and as you do print everything you know about each pet

for name, pet in zip(names, pets):
    print(name + " is " + pet["kind"] + " the owner is " + pet["owner"].title() + ".")

第二 - 将名称添加到字典中:

jumbo = {"name": "jumbo", "kind": "cat",
         "owner": "Rahma",
         }

snoopy = {"name": "snoopy", "kind": "dog",
          "owner": "fahad",
          }

shilla = {"name": "shilla", "kind": "bird",
          "owner": "farooq",
          }
for pet in pets:
    print(pet["name"] + " is " + pet["kind"] + " the owner is " + pet["owner"].title() + ".")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 2018-04-10
    • 2017-03-03
    • 1970-01-01
    相关资源
    最近更新 更多