Python:从txt-fi正确排序和打印数据

2024-03-29 01:41:15 发布

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

我的任务是为学生创建一个测试代码。它也能让老师们看到一个学生与班上其他同学相比有多好。学生完成测试后,其“用户名”和“正确答案”将存储到文本文件(我代码中实际工作的部分)。我设法阻止我的代码在同一个学生每次重考时都创建一个新用户名。当用户选择“if status==1:”时,上述所有操作都会发生。(状态1为学生,状态2为教师)。在

当选择状态2时,会询问教师要查看的班级。选择一个后,最新的3个分数和用户名应进行排序:

  1. 按字母顺序排列,每个学生的考试成绩最高
  2. 从最高分到最低分
  3. 按平均分,从高到低

到目前为止,我为状态2得出的结论是:

elif status == 2:
while True:
    try:
        users_class2 = int(input("Which class would you like to view? (1,2 or 3)"))
    except ValueError:
        print("Please enter a number!")
    else:
        if users_class2 not in {1,2,3}:
            print("Please enter a number in {1,2,3}!")
        else:
            break

if users_class2 == 1:
    val=[]
    keys=[]
    i=0
    l=[]
    lines=open('class1.txt','r').readlines()
    for line in lines:
      try:
        val.append(int(line))
      except:
        keys.append(line)

    for i in range(0,len(val),3):
     h=val[i:i+3]
     h.sort()
     l.append(h[::-1])
    print ("Sort the test results alphabetically and show the students highest score.\n")
    for i,j in zip(keys,l):
        print ("{},{}".format(i,j))

    print ("Sort by the average score, highest to lowest.")
    avlist=[float(sum(i))/len(i) for i in l ]
    print ("{}".format(avlist))
    while(len(avlist)):
        for i,j in zip(keys,avlist):
            if j==max(avlist):
              print ("{},{}".format(i,j))
              avlist.remove(j)

    print ("'\nSort by the highest score, highest to lowest.\n")
    hlist=[max(i) for i in l ]
    hlist.sort()
    hlist=hlist[::-1]
    for k in hlist:
        for i,j in zip(keys,l):
            if max(j)==k:
                print ("{},{}".format(i,j))

上面的代码只显示了一个if语句,用于“users\u class2”。对于“class2.txt”和“class3.txt”,此操作重复两次。在

选择一个类后,我的代码应该输出如下内容:

Sorted the test results alphabetically and shows the students highestscore.

艾伦,8,7,8

鲍勃,9,9,8

查理,3,4,5

Sort by the average score, highest to lowest.

鲍勃,9,9,8

艾伦,8,7,8

查理,3,4,5

Sort by the highest score, highest to lowest.

鲍勃,9,9,8

艾伦,8,7,8

查理,3,4,5

但我得到的却是:

Sort the test results alphabetically and show the students highest score.

Sort by the average score, highest to lowest.

[]'

Sort by the highest score, highest to lowest.

我已经为此工作了一段时间了,但没有什么运气。如果有人能帮我找到解决办法,我将不胜感激。如果你看到任何地方,我可以使我的代码有效,请这样说。谢谢。在


Tags: theto代码inforbyifsort
1条回答
网友
1楼 · 发布于 2024-03-29 01:41:15

if users_class2 not in {1,2,3}:

真的应该是

if users_class2 not in [1,2,3]:

试着打印出val和keys是什么,它们是否如您所期望的那样打印出数据?在


所以从你的代码来看,你似乎在试图从一个文本文件中读取,然后将它们添加到keys和{},对吗?在

您可以尝试添加以下语句以进行调试,以查看“val”是否按预期填充:

print "val is"
print val
print "====="

您可以将其添加到for循环的正上方for i in range(0,len(val),3):

相关问题 更多 >