gpt4 book ai didi

python - 如何对文件中的特定信息进行排序

转载 作者:行者123 更新时间:2023-11-28 17:36:38 25 4
gpt4 key购买 nike

我有一个预制的文本文件,里面有人名和分数。他们每个人都有三个分数,每个分数由制表符分隔。

John    12    13    21
Zack 14 19 12
Tim 18 22 8
Jill 13 3 22

现在,我的目标是按字母顺序对名称进行排序,只显示最高分。看起来像这样:

Jill   22
John 21
Tim 18
Zack 19

文件排序后,我想在 python shell 上打印它。我已经定义了代码,因为我将把它实现到我创建的其他代码中。

from operator import itemgetter

def highscore():
file1 = open("file.txt","r")
file1.readlines()
score1 = file1(key=itemgetter(1))
score2 = file1(key=itemgetter(2))
score3 = file1(key=itemgetter(3))


def class1alphabetical():
with open('file.txt') as file1in:
lines = [line.split('/t') for line in file1in]
lines.sort()
with open('file.txt', 'w') as file1out:
for el in lines:
file1out.write('{0}\n'.format(' '.join(el)))
with open('file.txt','r') as fileqsort:
for line in file1sort:
print(line[:-1])
file1sort.close

classfilealphabetical()

我使用了其他问题的信息,例如:Sorting information from a file in pythonPython : Sort file by arbitrary column, where column contains time values

但是,我仍然不知道现在该做什么。

最佳答案

哇,你做的事情似乎有点太复杂了。

这是一个粗略的想法。

#this will get your folks in alpha
lines = f.readlines()
lines.sort()

#now, on each line, you want to split (that attrgetter is too complicated and
#blows up if <> 3 grades.

# use the special feature of split() with no parameter to remove all spaces and \t characters
fields = line.split()
name, grades = fields[0], fields[1:]

#cast your grades to integers
grades = [int(grade) for grade in grades]

#sort and pick the last one
grades.sort()
highest = grades[-1]

#or... use max as suggested
highest = max(grades)

#write to output file....

另一条建议,为您的文件使用带有上下文管理器的打开,它们可以嵌套。关闭资源是行为良好的 pgms 的主要组成部分。

with open("/temp/myinput.txt","r") as fi:
....

关于python - 如何对文件中的特定信息进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29810515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com