我对Python非常陌生,我正在try 将CSV文件中的属性传递到一个类中,然后try 打印该类中的特定属性.

这是我的try ,但我意识到我离正确的解决方案还很远.

import csv

class Pokemon:
    def __init__(self, name, type1, type2, Atk, Def, SpAtk, SpDef, Spd, Health):
        self.name = name
        self.type1 = type1
        self.type2 = type2
        self.Atk = Atk
        self.Def = Def
        self.SpAtk = SpAtk
        self.SpDef = SpDef
        self.Spd = Spd
        self.Health = Health

    def pokeprint(self):
        print(f"{self.Atk}")

Pokemon_list = []

with open('Pokemon.csv', 'r') as f:
    reader = csv.reader(f)
    next(reader, None)
    for row in reader:
        Pokemon_list.append(Pokemon(row[0], row[1], row[2], int(row[3]), int(row[4]), int(row[5]), int(row[6]), int(row[7]), int(row[8])))

pokeprint(Bulbasaur)

以下是CSV文件中的几行代码:

Bulbasaur,Grass,Poison,45,49,49,65,65,45
Ivysaur,Grass,Poison,60,62,63,80,80,60
Venusaur,Grass,Poison,80,82,83,100,100,80

推荐答案

一种可能的解决方案是创建一个Pokemons字典,其中键是Pokemons的名称,值是类Pokemon的实例.例如:

import csv

class Pokemon:
    def __init__(self, name, type1, type2, Atk, Def, SpAtk, SpDef, Spd, Health):
        self.name = name
        self.type1 = type1
        self.type2 = type2
        self.Atk = Atk
        self.Def = Def
        self.SpAtk = SpAtk
        self.SpDef = SpDef
        self.Spd = Spd
        self.Health = Health

    def pokeprint(self):
        print(f"{self.Atk}")

Pokemon_dct = {}

with open('data.csv', 'r', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        Pokemon_dct[row[0]] = Pokemon(row[0], row[1], row[2], int(row[3]), int(row[4]), int(row[5]), int(row[6]), int(row[7]), int(row[8]))

Pokemon_dct['Bulbasaur'].pokeprint()

打印:

45

Python相关问答推荐

在Python中管理多个OpenGVBO和VAO实例

我必须将Sigmoid函数与r2值的两种类型的数据集(每种6个数据集)进行匹配,然后绘制匹配函数的求导.我会犯错

Python多处理:当我在一个巨大的pandas数据框架上启动许多进程时,程序就会陷入困境

try 与gemini-pro进行多轮聊天时出错

仿制药的类型铸造

为什么tkinter框架没有被隐藏?

管道冻结和管道卸载

大小为M的第N位_计数(或人口计数)的公式

切片包括面具的第一个实例在内的眼镜的最佳方法是什么?

Python解析整数格式说明符的规则?

当递归函数的返回值未绑定到变量时,非局部变量不更新:

Plotly Dash Creating Interactive Graph下拉列表

如何合并两个列表,并获得每个索引值最高的列表名称?

从Windows Python脚本在WSL上运行Linux应用程序

如何更改groupby作用域以找到满足掩码条件的第一个值?

Gekko中基于时间的间隔约束

在Python中从嵌套的for循环中获取插值

如何在FastAPI中替换Pydantic的constr,以便在BaseModel之外使用?'

如何将泛型类类型与函数返回类型结合使用?

在Django中重命名我的表后,旧表中的项目不会被移动或删除