【问题标题】:Python list, file sortPython列表,文件排序
【发布时间】:2013-09-30 15:27:18
【问题描述】:
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

当我运行我收到的程序时:

罗伯特 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

我正在尝试让数据按字母顺序显示:

布列塔尼 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

我曾尝试使用 .sort() 或 sorted(set(x)) 进行排序,但我不断收到错误消息。我不想对文件本身进行排序,但我需要在读取文件后对其进行排序,然后再打印数字和平均值。谢谢!非常感谢任何帮助!

【问题讨论】:

  • 你可以使用elif,而不是无限嵌套。

标签: file list sorting python-2.7 alphabetical


【解决方案1】:

你可以试试下面的,

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

然后继续split 并处理每一行。

【讨论】:

  • 或者更简洁地说:lines = sorted(grades_list),它既能吞下线条,又能立即对它们进行排序。
猜你喜欢
  • 2010-12-25
  • 2011-08-25
  • 1970-01-01
  • 2015-09-16
  • 1970-01-01
  • 2011-05-10
  • 1970-01-01
相关资源
最近更新 更多