TypeError:字符串索引必须是整数

时间:2014-05-26 02:09:29

标签: python

所以,我试图为Pokédex制作代码,并且我有以下代码段来打印出神奇宝贝的统计数据。请注意,在这三个词之前还有715个其他词典:

Xerneas = {'HP': 126, 'Atk': 131, 'Def': 95, 'SAtk': 131, 'SDef': 98, 'Spd': 99,
           'Ability': "Fairy Aura", 'Type': "Fairy"}
Yveltal = {'HP': 126, 'Atk': 131, 'Def': 95, 'SAtk': 131, 'SDef': 98, 'Spd': 99,
           'Ability': "Dark Aura", 'Type': "Dark/Flying"}
Zygarde = {'HP': 108, 'Atk': 100, 'Def': 121, 'SAtk': 81, 'SDef': 95, 'Spd': 95,
           'Ability': "Aura Break", 'Type': "Dragon/Ground"}

Mode = input('Which mode? ')
if Mode == "Pokedex":
    Pokemon = input("Which Pokemon? ")
    print(Pokemon['HP'],
          Pokemon['Atk'],
          Pokemon['Def'],
          Pokemon['SAtk'],
          Pokemon['SDef'],
          Pokemon['Spd'],
          Pokemon['Ability'],
          Pokemon['Type'])

然后我尝试运行我的代码并调用Zygarde的信息,但出现了以下错误:

Traceback (most recent call last):
  File "/Users/Cobalt/Documents/Python/Pokédex.py", line 154, in <module>
    print(Pokemon['HP'],
TypeError: string indices must be integers
>>> 

这个问题有一个简单的解决方案吗?如有必要,我愿意重新格式化718个词典。

顺便说一句,这是我在这个网站上的第一个问题,所以请不要对我太苛刻。

3 个答案:

答案 0 :(得分:3)

你需要像这样创建一个多维数组

pokemon = { 'Xerneas':  {'HP': 126, 'Atk': 131, 'Def': 95, 'SAtk': 131, 'SDef': 98, 'Spd': 99,
           'Ability': "Fairy Aura", 'Type': "Fairy"},
  'Yveltal': {'HP': 126, 'Atk': 131, 'Def': 95, 'SAtk': 131, 'SDef': 98, 'Spd': 99,
           'Ability': "Dark Aura", 'Type': "Dark/Flying"},
  'Zygarde': {'HP': 108, 'Atk': 100, 'Def': 121, 'SAtk': 81, 'SDef': 95, 'Spd': 95,
           'Ability': "Aura Break", 'Type': "Dragon/Ground"}
}

然后当你要求使用哪个口袋妖怪时:

    pokemon_type = input("Which Pokemon? ")
    print(pokemon[pokemon_type]['HP'],
          pokemon[pokemon_type]['Atk'],
          pokemon[pokemon_type]['Def'],
          pokemon[pokemon_type]['SAtk'],
          pokemon[pokemon_type]['SDef'],
          pokemon[pokemon_type]['Spd'],
          pokemon[pokemon_type]['Ability'],
          pokemon[pokemon_type]['Type'])

答案 1 :(得分:1)

Pokemon = input("Which Pokemon? ")

这使Pokemon成为一个字符串。然后,您可以通过执行以下操作来尝试访问此字符串:

Pokemon['HP']

现在解释器抱怨因为HP不是字符串上下文中的有效索引。 我猜你打算在这里找一本字典?

你可能想做的事情就是这样:

制作一个包含所有口袋妖怪的字典,例如我们可以称之为pokemon_dict

pokemon_dict = { "xerneas" : Xerneas, .....}

selection = input("Which Pokemon? ")
pokemon_selected = pokemon_dict[selection]
print(pokemon_selected['HP'])

答案 2 :(得分:1)

本声明

Pokemon = input("Which Pokemon? ")

Pokemon设置为字符串。