简体   繁体   English

Python列表,文件排序

[英]Python list, file sort

grades_list=open('student_grades.txt','r')
for x in grades_list.readlines():
ft=1
hf=0
hm1=0
hm2=0
hm3=0
hm4=0
z=x.split()

for w in z:

    if ft==1:
        ft=0
        hm=0
        name=w
    else:
        if hf==1:
            hf=0
            if hm==1:
               hm1=int(w)
            else:
                if hm==2:
                   hm2=int(w)
                else:
                    if hm==3:
                        hm3=int(w)
                    else:
                        if hm==4:
                            hm4=int(w)
        else:
            if w=='HM1':
                hm=1
                hf=1
            else:
                if w=='HM2':
                    hm=2
                    hf=1
                else:
                    if w=='HM3':
                        hm=3
                        hf=1
                    else:
                        if w=='HM4':
                            hm=4
                            hf=1

        list_values = [hm1, hm2, hm3, hm4]
        average = float(sum(list_values)) / len(list_values)
        print hm1, hm2, hm3, hm4, average

When I run the program I receive: 当我运行程序时,我收到:

Robert 0 90 80 92 65.5 Britany 98 92 0 0 47.5 Don 86 93 100 94 93.25 Charles 86 0 0 96 45.5 Sam 90 0 70 0 40.0 罗伯特0 90 80 92 65.5贿赂98 92 0 0 47.5唐86 93 100 94 93.25查尔斯86 0 0 96 45.5萨姆90 0 70 0 40.0

I am trying to get the data to appear in alphabetical order: 我试图使数据按字母顺序显示:

Britany 98 92 0 0 47.5 Charles 86 0 0 96 45.5 Don 86 93 100 94 93.25 Robert 0 90 80 92 65.5 Sam 90 0 70 0 40.0 大不列颠98 92 0 0 47.5查尔斯86 0 0 96 45.5唐86 93 100 94 93.25罗伯特0 90 80 92 65.5萨姆90 0 70 0 40.0

I have tried sorting using .sort() or sorted(set(x)) but I keep getting errors. 我尝试使用.sort()或sorted(set(x))进行排序,但我一直收到错误消息。 I do NOT want to sort the file itself, but I need it to sort once it reads the file, before it prints the numbers and averages. 我不想对文件本身进行排序,但是我需要它在读取文件后进行排序,然后再打印数字和平均值。 Thank you! 谢谢! Any help is much appreciated! 任何帮助深表感谢!

You can try the following, 您可以尝试以下方法,

lines = grades_list.readlines()
lines.sort()

and then continue to split and process each line. 然后继续split和处理每一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM