Sorting information from a file in python

2019-09-07 01:11发布

问题:

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

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

回答1:

  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.

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


回答2:

So i would first of all isolate all the lines:

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

So i will continue assuming I have a list called lines 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 will firstly sort the line by name

lines = sorted(lines)

Then for each line you want to isolate the marks, sort them and print them 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])