将列表转换为多值字典
问题描述:
我有一个列表,例如:将列表转换为多值字典
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
答
递归函数切了原有的列表和字典解析创建字典:
# 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']}
在每个宠物小精灵之后,你总是在列表中有一个空字符串吗? –
是的。 (谢谢你beautifulsoup)。 – avereux