【发布时间】:2019-03-04 15:23:15
【问题描述】:
该字典将农场动物存储为键,将它们的位置存储为值。
id_name_dict = {
'cat': 'barn', 'dog': 'field', 'chicken': 'coop',
'sheep': 'pasture', 'horse': 'barn', 'cow': 'barn'
}
此列表存储了我想知道其位置的农场动物的名称
wanted_farm_animals = ['cat,', 'dog', 'horse']
所需的输出是一个带有wanted_farm_animals 位置的新列表
n = ['barn', 'field', 'barn']
这是我尝试执行此操作的代码
n = []
for animal, location in id_name_dict.items():
for a in wanted_farm_animals:
if a == animal:
n.append(location)
print(n)
但是,输出并不完整。只是
['field', 'barn']
如何获得正确的期望输出?
【问题讨论】:
-
@meowgoesthedog 鉴于您的用户名,您必须是农场动物方面的专家;)
-
wanted_farm_animals 列表中的“猫”后面多了一个逗号
-
知道了!谢谢。
标签: python list dictionary