gpt4 book ai didi

python - 将列表转换为多值字典

转载 作者:行者123 更新时间:2023-12-03 20:22:00 25 4
gpt4 key购买 nike

我有一个这样的列表:

pokemonList = ['Ivysaur', 'Grass', 'Poison', '', 'Venusaur', 'Grass', 'Poison', '', 'Charmander', 'Fire', ''...]

注意模式是'Pokemon name', 'its type', ''...next pokemon

口袋妖怪有单型和双型两种形式。我如何编写此代码,以便每个口袋妖怪( key )都将其各自的类型应用为它的值?

到目前为止我得到了什么:

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

关于python - 将列表转换为多值字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33510427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com