python – 将列表转换为多值dict
发布时间:2020-12-20 11:46:47 所属栏目:Python 来源:网络整理
导读:我有一个列表: pokemonList = ['Ivysaur','Grass','Poison','','Venusaur','Charmander','Fire',''...] 请注意,模式是’口袋妖怪名称’,’它的类型’,”…下一个口袋妖怪 口袋妖怪有单一和双重形式.我如何对此进行编码,以便每个口袋妖怪(键)都将其各自的类
我有一个列表:
pokemonList = ['Ivysaur','Grass','Poison','','Venusaur','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',Charmander:['Fire']} 解决方法
只需迭代列表并适当地构造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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |