python – 将列表转换为多值dict

我有一个列表:

pokemonList = ['Ivysaur', 'Grass', 'Poison', '', 'Venusaur', 'Grass', 'Poison', '', 'Charmander', 'Fire', ''...]

请注意,模式是’口袋妖怪名称’,’它的类型’,”…下一个口袋妖怪

口袋妖怪有单一和双重形式.我如何对此进行编码,以便每个口袋妖怪(键)都将其各自的类型应用为其值?

到目前为止我得到了什么:

types = ("", "Grass", "Poison", "Fire", "Flying", "Water", "Bug","Dark","Fighting", "Normal","Ground","Ghost","Steel","Electric","Psychic","Ice","Dragon","Fairy")
pokeDict = {}
    for pokemon in pokemonList:
        if pokemon not in types:
            #the item is a pokemon, append it as a key
        else:
            for types in pokemonList:
                #add the type(s) as a value to the pokemon

正确的字典将如下所示:

{Ivysaur: ['Grass', 'Poison'], Venusaur['Grass','Poison'], Charmander:['Fire']}

最佳答案 只需迭代列表并适当地构造dict的项目.

current_poke = None
for item in pokemonList:
    if not current_poke:
        current_poke = (item, [])
    elif item:
        current_poke[1].append(item)
    else:
        name, types = current_poke
        pokeDict[name] = types
        current_poke = None
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞