如果我理解正确的话,你是在问如何才能动态创建变量。操纵globals()
dict 创建新变量不是一个好主意,您应该使用列表或字典来存储 csv 数据。
您似乎需要一个列表,所以:
- 定义列表 (
student_list
在下面的例子中)。
- 打开 csv 文件。
- 创建一个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.