对文件中的某些信息进行排序
Sorting certain info in a file
我正在制作一个程序,以最高分的字母顺序对文件进行排序。该文件有 4 个这样的名称,用制表符分隔:
Jeff 12 17 16
Dan 23 21 18
John 12 10 20
Mary 13 24 24
这是我的代码:
with open("file.txt","r") as f:
lines = f.readlines()
lines.sort()
fields = [line.split() for line in f]
name, grades = fields[0], fields[1:]
grades = [int(grade) for grade in grades]
grades.sort()
highest = max(grades)
with open('file.txt','w') as fout:
for el in lines:
fout.write('{0}\n'.format(' '.join(el)))
with open('file.txt','r') as fsort:
for line in fsort:
print(line[:-1])
fsort.close()
我不断收到列表值超出范围等错误;对于场线。谁能给我一个解决方案,让这段代码有效?
您需要使用 fields = [line.split() for line in lines]
,而不是 in f
。当调用 f.readlines()
时,文件指针最终移动到末尾,这意味着 fields
是一个空列表。
但是,我感觉 name, grades = fields[0], fields[1:]
不会按照您的意愿去做。以下内容应确保 name
和 grades
存储您想要的内容(根据提问者的要求进行大量编辑):
with open("class6Afile.txt","r") as f:
lines = f.readlines()
lines.sort()
with open('class6AfileOut.txt','w') as fout:
for line in lines:
fields = line.split()
name, grades = fields[0], fields[1:]
grades = [int(grade) for grade in grades]
grades.sort()
highest = max(grades)
grades = [str(grade) for grade in grades]
print name, grades
fout.write('{0} {1}\n'.format(name, ' '.join(grades)))
我正在制作一个程序,以最高分的字母顺序对文件进行排序。该文件有 4 个这样的名称,用制表符分隔:
Jeff 12 17 16
Dan 23 21 18
John 12 10 20
Mary 13 24 24
这是我的代码:
with open("file.txt","r") as f:
lines = f.readlines()
lines.sort()
fields = [line.split() for line in f]
name, grades = fields[0], fields[1:]
grades = [int(grade) for grade in grades]
grades.sort()
highest = max(grades)
with open('file.txt','w') as fout:
for el in lines:
fout.write('{0}\n'.format(' '.join(el)))
with open('file.txt','r') as fsort:
for line in fsort:
print(line[:-1])
fsort.close()
我不断收到列表值超出范围等错误;对于场线。谁能给我一个解决方案,让这段代码有效?
您需要使用 fields = [line.split() for line in lines]
,而不是 in f
。当调用 f.readlines()
时,文件指针最终移动到末尾,这意味着 fields
是一个空列表。
但是,我感觉 name, grades = fields[0], fields[1:]
不会按照您的意愿去做。以下内容应确保 name
和 grades
存储您想要的内容(根据提问者的要求进行大量编辑):
with open("class6Afile.txt","r") as f:
lines = f.readlines()
lines.sort()
with open('class6AfileOut.txt','w') as fout:
for line in lines:
fields = line.split()
name, grades = fields[0], fields[1:]
grades = [int(grade) for grade in grades]
grades.sort()
highest = max(grades)
grades = [str(grade) for grade in grades]
print name, grades
fout.write('{0} {1}\n'.format(name, ' '.join(grades)))