use*_*420 6 object python-3.x import-csv
我是一个初学者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])
Run Code Online (Sandbox Code Playgroud)
但是,我需要它自动工作,而不必每次都手动输入数据,因为会有数千个更新 - 因此需要能够从 csv 中引入数据。
csv文件格式为:john, 85, 21, 1 bob, 45, 9.5, 2
Student 对象将具有分数属性(第 2 列和第 3 列作为元组)以及排名属性(第 4 列)。所需的对象格式与上面手动代码生成的格式相同。
手动代码生成的所需格式的一个示例是,当我在手动代码之后执行以下打印时:
print(" John: score1={0[0]:.3f} score2={0[1]:.3f}".format(john.skill))
Run Code Online (Sandbox Code Playgroud)
我得到这个结果:
约翰: score1=25.000 score2=8.333
干杯,
史蒂夫
如果我理解正确的话,您是在问如何动态创建变量。操作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
Run Code Online (Sandbox Code Playgroud)
尝试以下代码:
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.
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7494 次 |
最近记录: |