2015-11-03 179 views
3

我有一個列表,例如:將列表轉換爲多值字典

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

回答

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 
1

這是低技術的做法:迭代列表並收集記錄。

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

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

一行。不是因爲它有用,而是因爲我開始嘗試並且不得不完成。

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