因此,我需要编写一个代码来检查口袋妖怪是否具有类型,如果存在,它将把该口袋妖怪名称与所有其他拥有相同类型的口袋妖怪一起添加到字典中。有关此的所有信息都存储在一个csv文件中。缩进看起来也很奇怪,但是在我的实际文件中已经正确缩进了。
import sqlite3
import csv
SEP = ','
def get_pokemon_stats():
"""Reads the data contained in a pokemon data file and parses it into
several data structures.
Args: None
Returns:
-a dict where:
-each key is a pokemon type (str). Note that type_1 and type_2
entries are all considered types. There should be no special
treatment for the type NA; it is considered a type as well.
-each value is a list of all pokemon names (strs) that fall into
the corresponding type
"""
type_list = []
poketype = []
pokewith_type = []
DATA_FILENAME = 'pokemon.csv'
with open('pokemon.csv', 'r') as csv_file:
csv_file.readline()
for line in csv_file:
list_of_values = line.strip().split(SEP)
type_list.extend(list_of_values[6:8])
for i in range(len(type_list)):
if type_list[i] not in poketype:
poketype.append(type_list[i])
poketypelist = (list_of_values[1], list_of_values[6:8])
for i in range(len(poketypelist) - 1):
if type_list[i] in poketype:
pokemon_by_type[ type_list[i]] = poketypelist[i]
我的问题:
我不知道如何使python识别列表中的口袋妖怪是否具有类型,以及是否确实将其添加到字典中。
一个例子;如果bulbasaur是毒草,那么在词典中,bulbasaur应该出现在毒药和草键旁边。
我的CSV文件如下:
它有口袋妖怪的名字,然后是一堆其他东西,然后第三列和第四列是这两种类型。
答案 0 :(得分:0)
我假设第2列是神奇宝贝的名字,第6列和第7列是它的类型。而且由于您不能使用熊猫,
我不知道您到底要问什么,但这就是我想您要寻找的东西
def get_pokemon_stats():
"""
Reads a csv file and returns a Dict of pokemons grouped under their type
"""
type_list = []
pokemon_by_type_dict = {}
DATA_FILENAME = 'pokemon.csv'
with open('pokemon.csv', 'r') as csv_file:
csv_file.readline()
for line in csv_file:
list_of_values = line.split(",")
for i in list_of_values[6:8]:
if i not in type_list:
type_list.append(i)
pokemon_by_type_dict[i] = [] # Each "Type" key is a list of pokemons, change it if you want to
pokemon_by_type_dict[i].append(list_of_values[1])
return pokemon_by_type_dict # Returns the pokemon dict
这是您要找的代码吗?
答案 1 :(得分:0)
data.csv
name,stuff,stuff,type1,type2
bulbasaur,who knows,who knows,poison,grass
fakeasaur,who knows,who knows,poison,grass
pikachu,who knows,who knows,lightning,rat
pokemon.py
#!/bin/python
the_big_d = {}
with open('data.csv', 'r') as csv_file:
csv_file.readline()
for line in csv_file:
l = line[0:-1].split(',')
if l[3] not in the_big_d:
the_big_d[l[3]] = [l[0]]
else:
the_big_d[l[3]].append(l[0])
if l[4] not in the_big_d:
the_big_d[l[4]] = [l[0]]
else:
the_big_d[l[4]].append(l[0])
print(the_big_d)
输出:
{'poison': ['bulbasaur', 'fakeasaur'], 'grass': ['bulbasaur', 'fakeasaur'], 'lightning': ['pikachu'], 'rat': ['pikachu']}