如何限制列表python3中的值数量

2024-10-02 04:18:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个程序,询问用户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分。在


Tags: 文件csvthe代码程序view列表for
3条回答

假设数据文件中每个学生的分数超过1分,例如:

Josh Hill,8,4,0,1,2
Lisa Hale,7,6,3,4,5
Max Wood,10,12,6,7,8
Sally Jones,5,5,9,10,11
David West,2,8,12,13,14

您可以使用slice syntax从每行中提取最后三个分数,如下所示:

^{pr2}$

输出:

classonelist:
  Josh Hill,      last three scores: [0, 1, 2]
  Lisa Hale,      last three scores: [3, 4, 5]
  Max Wood,       last three scores: [6, 7, 8]
  Sally Jones,    last three scores: [9, 10, 11]
  David West,     last three scores: [12, 13, 14]

你想从名单上取最后3分吗?Slicing就是答案:

>>>mylist = [1,2,3,4,5,6]
>>>mylist[-3:]
[4,5,6]

这是假设您使用append作为增加列表的方法。在

您可以使用deque,设置maxlen=3,这样您只保留最新的3个:

from collections import deque

deq = deque(maxlen=3)

如果你想把最新的三个分数保存在一个文件中,你需要通过覆盖来更新分数,如果是这样的话,使用带有json的dict可能是一种更容易存储数据的方法,使用键来访问学生的分数。在

相关问题 更多 >

    热门问题