Sorting information from a file in python
I have a file .txt
that contains the following information, which displays the username and then the 3 scores they typed in the quiz:
callum,10,7,9 carl,10,10,10 hollie,1,4,7 brad,4,8,3 kyle,7,2,0
I would like sort
to display the highest score of users in alphabetical order after their name.
0
source to share
2 answers
- Read the contents of the file.
- Use the method
readlines()
to read lines from a file. - Use
split()
for name and rating. - Add to the dictionary:
Name
isKey
andValue
- total score. - Get everything
keys
from the results dictionary. - User
sort()
method to sort alphabetically. - Print the result in alphabetical order.
code
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])
Output:
$ 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
+1
source to share
So, I would first highlight all the lines:
with open('filename') as f:
lines = f.readlines()
So, I will continue to assume that I have a list called strings with the following content:
lines = ["callum,10,7,9","carl,10,10,10","hollie,1,4,7","brad,4,8,3","kyle,7,2,0"]
Then I first sort the string by name
lines = sorted(lines)
Then, for each line, you want to isolate the labels, sort them, and print back:
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])
0
source to share