此字典将农场动物存储为键,将它们的位置存储为值。
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']如何获得正确的期望输出?
发布于 2019-03-04 23:29:44
简单的列表理解如何?
id_name_dict = {
'cat': 'barn', 'dog': 'field', 'chicken': 'coop',
'sheep': 'pasture', 'horse': 'barn', 'cow': 'barn'
}
wanted_farm_animals = ['cat', 'dog', 'horse']
result = [v for k,v in id_name_dict.items() if k in wanted_farm_animals]
# ['barn', 'field', 'barn']发布于 2019-03-04 23:38:00
您可以将wanted_farm_animals列表映射到绑定到id_name_dict字典的dict.get方法:
n = list(map(id_name_dict.get, wanted_farm_animals))通过使用dict.get方法,对于在wanted_farm_animals列表中但不在id_name_dict字典的键中的项,您将获得默认值None,而不是KeyError异常。
https://stackoverflow.com/questions/54986276
复制相似问题