将列表转换为多值字典

Converting a list into a multi-valued dict

我有一个这样的列表:

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

注意模式是'Pokemon name', 'its type', ''...next pokemon

口袋妖怪有单型和双型两种形式。我如何编写代码以便每个宠物小精灵(钥匙)都将其各自的类型应用为它的值?

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

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']}

只需迭代列表并适当地为字典构造项目..

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

这是一种低技术含量的方法:遍历列表并随时收集记录。

key = ""
values = []
for elt in pokemonList:
    if not key:
        key = elt
    elif elt:
        values.append(elt)
    else:
        pokeDict[key] = values
        key = ""
        values = []

用于分割原始列表的递归函数,以及用于创建字典的字典理解:

# Slice up into pokemon, subsequent types
def pokeSlice(pl):
    for i,p in enumerate(pl):
        if not p:
            return [pl[:i]] + pokeSlice(pl[i+1:])      
    return []

# Returns: [['Ivysaur', 'Grass', 'Poison'], ['Venusaur', 'Grass', 'Poison'], ['Charmander', 'Fire']]

# Build the dictionary of 
pokeDict = {x[0]: x[1:] for x in pokeSlice(pokemonList)}

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

一个班轮。不是因为它有用,而是因为我开始尝试并且不得不完成。

>>> pokemon = ['Ivysaur', 'Grass', 'Poison', '', 'Venusaur', 'Grass', 'Poison', '', 'Charmander', 'Fire', '']
>>> { pokemon[i] : pokemon[i+1:j] for i,j in zip([0]+[k+1 for k in [ brk for brk in range(len(x)) if x[brk] == '' ]],[ brk for brk in range(len(x)) if x[brk] == '' ]) }
{'Venusaur': ['Grass', 'Poison'], 'Charmander': ['Fire'], 'Ivysaur': ['Grass', 'Poison']}