在python中对文件中的信息进行排序 [英] Sorting information from a file in python
本文介绍了在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.
推荐答案
- 读取文件内容.
- 使用
readlines()
方法从文件中读取行. - 使用
split()
获取名称和分数. - 加入字典:
Name
是Key
,Value
是总分. - 从结果字典中获取所有
键
. - 使用
sort()
方法按字母对列表进行排序. - 按字母顺序打印结果.
- Read file content.
- Use
readlines()
method to read lines from file. - Use
split()
to get Name and score. - Add in dictionary:
Name
isKey
andValue
is total score. - Get all
keys
from the result dictionary. - User
sort()
method to sort list by alphabets. - 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屋!
查看全文