首页 > 解决方案 > 必须找到被 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和学习很陌生。请帮我解决它。

标签: dictionarynested

解决方案


您可以像这样遍历字典:

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

推荐阅读