[英]How to sort a text file into a list consisting of tuples and then appending to the list in 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
当我运行程序时,我收到:
罗伯特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))进行排序,但我一直收到错误消息。 我不想对文件本身进行排序,但是我需要它在读取文件后进行排序,然后再打印数字和平均值。 谢谢! 任何帮助深表感谢!
您可以尝试以下方法,
lines = grades_list.readlines()
lines.sort()
然后继续split
和处理每一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.