将列表转换成含有多个值的字典

3

我有一个列表如下:

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

在每个 Pokemon 后面,您的列表中总是有一个空字符串吗? - Joshua Grigonis
是的。(谢谢beautifulsoup) - avereux
4个回答

3
只需遍历列表并根据字典的要求构建项目即可。
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

2
递归函数用于切分原始列表,字典解析用于创建字典:
# 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']}

1
这是一种简单的方法:按顺序遍历列表并在进行遍历时收集记录。
key = ""
values = []
for elt in pokemonList:
    if not key:
        key = elt
    elif elt:
        values.append(elt)
    else:
        pokeDict[key] = values
        key = ""
        values = []

这段代码真的很整洁,易于阅读。我希望我能接受两个答案! - avereux
没问题,接受哪个答案都是你的权利。(但是你可以点赞任意多个答案;-) - alexis

1

这是一句简短的话,不是因为它很有用,而是因为我开始尝试了,就必须把它完成。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接