# 已知有一个文本文件data.txt,内容如下: # 姓名,语文,数学,英语,理综 # 刘婧,124,137,145,260 # 张华,116,143,139,263 # 邢昭林,120,130,148,255 # 鞠依依,115,145,131,240 # 黄丽萍,123,108,121,235 # 赵越,132,100,112,210 # 现要求按照总分进行排序,将结果输出到result.txt中,内容包括三列,分别是名次、姓名和总分
with open("data.txt",encoding="utf-8") as f: list=f.readlines() list1=[] for i in range(1,len(list)): sum=0 for j in range(1,5): score=float(list[i].split(",")[j].strip()) sum+=score line=list[i].split(",")[0].strip(),sum list1.append(line) a = sorted(list1, key=lambda x: x[1], reverse=True) file=open("result.txt","w",encoding="utf-8") for i in range(len(a)): s = '' for j in range(2): b=str(tuple(a[i])[j]) s=s+b s="第%s名"%(i+1)+s file.writelines(s+'\n') file.close()