我有一个文件,里面有很多学生的名字、分数和考试编号(按顺序排列),我想知道每个学生在哪一次考试中表现最好(从1分到5分,1分是最好的分数)。有些学生可能只考了一次,有些考了两次。文件如下所示:
student1,4.2,1
student2,1.02,1
student3,4.1,1
student4,2.089,1
student2,3.02,2
student3,2.54,2
student4,3.69,2
student5,1.34,2
我计划创建一个包含姓名、考试编号和分数的字典,然后检索最佳分数。我的代码如下所示:
with open('filename.csv') as f:
lines = f.readlines()
scores = {} #{ Name : { Exam_Number : score }
for line in lines:
n = re.match(r"(.*)\,(.*)\,(.*)",line)
student = n.group(1)
score = n.group(2)
exam_number = n.group.(3)
scores[name] = { exam_number : score } #HERE IS THE PROBABLE ERROR
#Obtain the best score per student and the number of the exam
best_exam = {}
for name in scores:
for num in scores[name]:
for score in scores[name][num]:
if name in best_sco:
for num_ext in best_sco[name]:
if best_sco[name][num] > num_ext:
best_sco[sample] = { num : amb }
else:
best_sco[name] = {num : amb }
我意识到,每当我试图为一个已经存在的名字加入一个新的考试号码:分数组合时,为那个名字存储的前一对就被删除了。例如,如果我调用student4的分数,只会出现对应于考试2的那一个,因为这是最后一个要读的,上一个被覆盖了。有没有一种方法可以用成对的键声明一个字典,然后考虑到某些键(但没有对)可能重复,遍历所有可能的对?你知道吗
编辑----------------------------------
以稍微不同的方式回答相同的问题(这可能会给熟悉Python和Perl的人敲响警钟)。在Python中是否有Perl's Multidimensional Hashes的等价物?你知道吗
使用defaultdict`?把分数放在一个列表中然后检索最高的一个?你可以使用csv来读取文件本身,这样你就不用使用regex了
你可以使用元组作为dict中的键,只要不存在重复的学生/考试组合
相关问题 更多 >
编程相关推荐