python - Sort Column in a file from high to low -


i have file has set of peoples scores. there 3 scores each person. able display highest score of person. however, not able print python shell, highest score in descending order. example:

persona    12 personb    14 personc    17 persond    11 

and want sorted descending order of score. should like:

personc    17 personb    14 persona    12 persond    11 

so far have created code, not know how continue:

with open("class.txt","r") file:          lines = file.readlines()      open('class.txt','w') fileout:          line in lines:              fields = line.split()              name, grades = fields[0], fields[1:]              grades = [int(grade) grade in grades]              grades.sort()              highest = str(max(grades))              grades = [str(highest) grade in grades]              rows = filter(none, [line.strip().split() line in open("file.txt", "r")])              data = [(name, int(highest)) name, highest in rows]          name, highest in sorted(data, key=itemgetter(1)):              print("{0:s} {1:d}".format(person, score))

this simple as:

from operator import itemgetter   rows = filter(none, [line.strip().split() line in open("data", "r")]) data = [(person, int(score)) person, score in rows]  person, score in sorted(data, key=itemgetter(1), reverse=true):     print "{0:s} {1:d}".format(person, score) 

nb: assumes input data void of erroneous data , general garbage. if input data not clean have expand bit further!

output:

$ python test_data.py  personc 17 personb 14 persona 12 persond 11 

update:

if data has garbage in describe in comment.

$ cat data persona    12 foo personb    14 bar personc    17 baz persond    11 

then above program have modified custom key example:

def sortkey(row):     return int(row[1])   rows = filter(none, [line.strip().split() line in open("data", "r")])  row in sorted(rows, key=sortkey, reverse=true):     print "{0:s} {1:s}".format(row[0], row[1]) 

which still produce teh same output:

$ python test_data.py  personc 17 personb 14 persona 12 persond 11 

Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -