I have the following in a text file:
('bob', '10')
('Ben', '10')
('Ben', '9')
('Ben', '8')
('Ben', '2')
('Ben', '6')
('Ben', '5')
('Ben', '5')
('Ben', '3')
('Ben', '2')
I would like to reorder it so that it is ordered by numbers going down, so that I can print them off in a high score table, however I cannot work out how to do this. Any help would be appreciated, thanks.
You can use ast.literal_eval
to parse the tuples and then pass them to sorted
:
import ast
from operator import itemgetter
def parse_item(s):
name, score = ast.literal_eval(s)
return name, int(score)
with open("infile", "r") as infile:
items = [parse_item(line.strip()) for line in infile]
for item in sorted(items, key=itemgetter(1), reverse=True):
print item
Or the concise but confusing way:
print ''.join(sorted(open('infile'), key=lambda l: -int(ast.literal_eval(l)[1]))),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With