【问题标题】:Converting a list into a multi-valued dict将列表转换为多值字典
【发布时间】:2016-02-04 06:33:06
【问题描述】:

我有一个这样的列表:

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

【问题讨论】:

  • 你的列表中是否总是在每个 pokemon 之后有一个空字符串?
  • 是的。 (谢谢美丽的汤)。

标签: python list python-3.x dictionary dictionary-comprehension


【解决方案1】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 这段代码读起来非常简洁明了。我希望我能接受这两个答案!
      • 没问题,接受您更喜欢的答案是您的特权。 (但是您可以根据需要投票给尽可能多的答案 ;-)
      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-26
        • 1970-01-01
        • 2022-11-14
        相关资源
        最近更新 更多