将列表转换为多值字典

问题描述:

我有一个列表,例如:将列表转换为多值字典

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

在每个宠物小精灵之后,你总是在列表中有一个空字符串吗? –

+0

是的。 (谢谢你beautifulsoup)。 – avereux

只是想迭代列表,并适当建设项目的字典..

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 = [] 
+0

这段代码真的很干净,轻松阅读。我希望我能接受这两个答案! – avereux

+0

没问题,接受你更喜欢的答案是你的特权。 (但是,您可以随心所欲地提供尽可能多的答案;-) – alexis

递归函数切了原有的列表和字典解析创建字典:

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