dictionary - 必须找到被 pokemon 捕获的rattatas、dittos 和 pidgeys 的总数,并分别分配给变量 r、d 和 p
问题描述
'''pokemon = {'Trainer1':
{'normal': {'rattatas':15, 'eevees': 2, 'ditto':1}, 'water': {'magikarps':3}, 'flying':
{'zubats':8, 'pidgey': 12}},
'Trainer2':
{'normal': {'rattatas':25, 'eevees': 1}, 'water': {'magikarps':7}, 'flying': {'zubats':3,
'pidgey': 15}},
'Trainer3':
{'normal': {'rattatas':10, 'eevees': 3, 'ditto':2}, 'water': {'magikarps':2}, 'flying':
{'zubats':3, 'pidgey': 20}},
'Trainer4':
{'normal': {'rattatas':17, 'eevees': 1}, 'water': {'magikarps':9}, 'flying': {'zubats':12,
'pidgey': 14}}}'''
'my answer:'
'''pokemon.keys()
pokemon['Trainer1']
{'normal': {'rattatas': 25, 'eevees': 1},
'water': {'magikarps': 7},
'flying': {'zubats': 3, 'pidgey': 15}}
pokemon['Trainer2']
{'normal': {'rattatas': 25, 'eevees': 1},
'water': {'magikarps': 7},
'flying': {'zubats': 3, 'pidgey': 15}}
pokemon['Trainer3']
{'normal': {'rattatas': 10, 'eevees': 3, 'ditto': 2},
'water': {'magikarps': 2},
'flying': {'zubats': 3, 'pidgey': 20}}'''
'但现在我被困住了,因为对我来说,简单的答案就是添加我可以看到的rattatas、dittos和pidgeys。但显然这不是一个技术性的答案。我对python和学习很陌生。请帮我解决它。
解决方案
您可以像这样遍历字典:
for trainer in pokemon:
# loop through keys
print(trainer)
for trainer in pokemon.keys():
# same as above
print(trainer)
for types in pokemon.values():
# loop through values
print(types)
for trainer, types in pokemon.items():
# loop though key,value pairs
print(trainer + " has " + str(types))
现在我们只需要循环pokemon
并使用嵌套的 for 循环来获取单个 pokemon 计数并将它们相加:
r = 0
d = 0
p = 0
for trainer, types in pokemon.items():
# now we can loop over a trainer's caught types
for type_group, pokemon_counts in types.items():
# now we can loop over the count of each pokemon in a type caught by the trainer
for name, count in pokemon_counts.items():
if name == "rattatas":
r += count
elif name == "ditto":
d += count
elif name == "pidgey":
p += count
print("Rattata: " + str(r))
print("Ditto: " + str(d))
print("Pidgey: " + str(p))
# Rattata: 67
# Ditto: 3
# Pidgey: 61
嵌套循环可以简化为此,因为您不需要前 2 个键,但如果您刚刚开始,可能更容易理解上述循环:
for types in pokemon.values():
for pokemon_counts in types.values():
for name, count in pokemon_counts.items():
if name == "rattatas":
r += count
elif name == "ditto":
d += count
elif name == "pidgey":
p += count
推荐阅读
- python - AttributeError: 'NoneType' 对象没有属性 'get_text' python web-scraping
- image - 在 Yocto 中构建后的 Image 文件夹的内容
- java - Kotlin - 无法推断泛型类型
- python - 通过 FTP 下载文件 NOAA
- r - 使用 R 的数据整理将一列拆分为两列
- javascript - 如何在用户输入时建议日期/时间?
- c# - 将 C# 表单添加到另一个表单中
- c# - 暂停其他线程并从两个线程一次在一个线程中运行执行
- android - 在 Google Play 中发布应用后,Google Drive Api 停止工作
- php - 无法安装 Laravel OSX Catalina