我有一个列表:
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 :(得分:3)
只需迭代列表并适当地为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
答案 1 :(得分: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']}
答案 2 :(得分:1)
这是执行此操作的低技术方法:迭代列表并随时收集记录。
key = ""
values = []
for elt in pokemonList:
if not key:
key = elt
elif elt:
values.append(elt)
else:
pokeDict[key] = values
key = ""
values = []
答案 3 :(得分:1)
一个班轮。不是因为它有用,而是因为我开始尝试并且必须完成。
let myRouteRequest = MKDirectionsRequest()
myrouteRequest.transportType = .Automobile
myRouteRequest.setSource(MKMapItem.mapItemForCurrentLocation())
myRouteRequest.setDestination(MKMapItem(myPlacemark))