在python中从文件中排序信息

2024-10-03 05:28:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个.txt文件,其中包含以下信息,其中显示用户名,然后显示他们在测验中获得的3个分数:

callum,10,7,9
carl,10,10,10
hollie,1,4,7
brad,4,8,3
kyle,7,2,0

我想sort按字母顺序显示用户名字后的最高分数。在


Tags: 文件用户txt信息顺序字母名字sort
2条回答

所以我首先要隔离所有的线:

with open('filename') as f:
    lines = f.readlines()

假设我将继续以下内容:

^{pr2}$

然后我将首先按名称对行进行排序

lines = sorted(lines)

然后,对于要隔离标记的每一行,将其排序并打印回原处:

for line in lines:
    #name is what there is before the first comma
    name = line[:line.find(",")]
    #marks are what there is after the second comma and are comma separated
    marks = line[line.find(",")+1:].split(",")
    #sort the marks
    marks = sorted(marks,key=int)

    #if you want to print only the highest
    print "%s,%s"%(name,marks[-1])
  1. 读取文件内容。在
  2. 使用readlines()方法从文件中读取行。在
  3. {and-score>使用
  4. 附加字典:NameKeyValue是总分。在
  5. 从结果字典中获取所有keys。在
  6. 用户sort()方法按字母表对列表排序。在
  7. 按字母顺序打印结果。在

代码

p = "/home/vivek/Desktop/test_input.txt"
result = {}
with open(p, "rb") as fp:
    for i in fp.readlines():
        tmp = i.split(",")
        try:
            result[(tmp[0])] = eval(tmp[1]) + eval(tmp[2]) + eval(tmp[3]) 
        except:
            pass

alphabetical_name =  result.keys()
alphabetical_name.sort()

for i in alphabetical_name:
    print "Name:%s, Highest score: %d"%(i, result[i])

输出:

^{pr2}$

相关问题 更多 >