我是一个初学者python用户。无法以所需的对象格式将数据从 csv 获取到 python 以满足 python 函数。
如果我在 python 中手动创建数据(而不是从 csv 中引入),则以下代码有效:
class Student(object):
pass
john = Student()
#score tuple
john.score = (85.0, 42.0/2.0)
bob = Student()
bob.score = (45.0, 19.0/2.0)
john.rank = 1
bob.rank = 2
ExternalCode.AdjustStudents([john, bob])
但是,我需要它自动工作,而不必每次都手动输入数据,因为会有数千个更新 - 因此需要能够从 csv 中引入数据。
.csv 文件格式为:
约翰, 85, 21, 1
鲍勃, 45, 9.5, 2
Student 对象将具有分数属性(第 2 列和第 3 列作为元组)以及排名属性(第 4 列)。所需的对象格式与上面手动代码生成的格式相同。
手动代码生成的所需格式的一个示例是,当我在手动代码之后执行以下打印时:
print(" John: score1={0[0]:.3f} score2={0[1]:.3f}".format(john.skill))
我得到这个结果:
约翰: score1=25.000 score2=8.333
干杯,
史蒂夫
最佳答案
如果我理解正确,你是在问如何才能create variables dynamically .操纵globals()
dict 创建新变量不是一个好主意,您应该使用列表或字典来存储您的 csv 数据。
你似乎需要一个列表,所以:
student_list
)。 csv.reader
. Student
实例并传递名称和数字。 student_list
. 所以如果你的 csv 文件看起来像这样,
name,score1,score2,rank
john,85,21,1
sarah,72,19,2
bob,45,19,3
试试下面的代码:
import csv
class Student:
def __init__(self, name, score, rank):
self.name = name
self.score = score
self.rank = rank
student_list = []
with open('temp.csv', newline='') as csv_file:
reader = csv.reader(csv_file)
next(reader, None) # Skip the header.
# Unpack the row directly in the head of the for loop.
for name, score1, score2, rank in reader:
# Convert the numbers to floats.
score1 = float(score1)
score2 = float(score2)
rank = float(rank)
# Now create the Student instance and append it to the list.
student_list.append(Student(name, (score1, score2), rank))
# Then do something with the student_list.
关于python-3.x - 如何从csv获取数据到python对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47128105/