我写了一个程序,询问用户5个随机数学问题,并将他们的名字和分数保存到一个csv文件。在
我只想我的列表存储每个学生最新的3个分数。如何在python3的列表中做到这一点?在
我现在的代码是:
import csv
print ("Welcome to the teacher view.\n"
"Here you can view the test results.\n")
option = int(input("Which class would you like view?\n"
"For Class 1 - enter 1: \n"
"For Class 2 - enter 2: \n"
"For Class 3 - enter 3: \n"))
if option ==1:
with open("classthree.csv")as classone:
classoneReader = csv.reader(classone)
classonelist=[]
for row in classoneReader:
row[1] = int(row[1])
classonelist.append(row[0:2])
print(classonelist)
我存储在csv文件中的代码示例如下:
乔希·希尔8 丽莎黑尔7 麦克斯伍德10 莎莉·琼斯5岁 大卫韦斯特2
程序应该读取这些信息并将其附加到一个列表中。我想显示每个学生的最新3分。在
假设数据文件中每个学生的分数超过1分,例如:
您可以使用slice syntax从每行中提取最后三个分数,如下所示:
^{pr2}$输出:
你想从名单上取最后3分吗?Slicing就是答案:
这是假设您使用
append
作为增加列表的方法。在您可以使用deque,设置
maxlen=3
,这样您只保留最新的3个:如果你想把最新的三个分数保存在一个文件中,你需要通过覆盖来更新分数,如果是这样的话,使用带有json的dict可能是一种更容易存储数据的方法,使用键来访问学生的分数。在
相关问题 更多 >
编程相关推荐