在python中对文件中的信息进行排序 [英] Sorting information from a file in python

查看:39
本文介绍了在python中对文件中的信息进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a .txt file that has the following information in it that displays a users name and then 3 scores that they have scored in a quiz:

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

我想将它sort按字母顺序显示在用户姓名后面的最高分.

I would like to sort it into alphabetical order displaying the users highest score after their name.

推荐答案

  1. 读取文件内容.
  2. 使用 readlines() 方法从文件中读取行.
  3. 使用 split() 获取名称和分数.
  4. 加入字典:NameKeyValue是总分.
  5. 从结果字典中获取所有.
  6. 使用 sort() 方法按字母对列表进行排序.
  7. 按字母顺序打印结果.
  1. Read file content.
  2. Use readlines() method to read lines from file.
  3. Use split() to get Name and score.
  4. Add in dictionary: Name is Key and Value is total score.
  5. Get all keys from the result dictionary.
  6. User sort() method to sort list by alphabets.
  7. Print result by alphabets order.

代码

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])

输出:

$ python test.py 
Name:brad, Highest score: 15
Name:callum, Highest score: 26
Name:carl, Highest score: 30
Name:hollie, Highest score: 12
Name:kyle, Highest score: 9

这篇关于在python中对文件中的信息进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆