我是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档案格式为:john,85、21、1 bob,45、9.5、2
学生对象将具有得分属性(第2列和第3列为元组)以及排名属性(第4列)。所需的对象格式将与上面的手动代码产生的格式相同。
手册代码产生的所需格式的一个示例是,当我在手册代码之后执行以下打印时:
print(" John: score1={0[0]:.3f} score2={0[1]:.3f}".format(john.skill))
我得到这个结果:
约翰:得分1 = 25.000得分2 = 8.333
干杯,
史蒂夫
如果我对您的理解正确,那么您在问如何动态创建变量。操作globals()
字典以创建新变量不是一个好主意,您应该使用列表或字典来存储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.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句