Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order these lines for a highscore table in Python

Tags:

python

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.

like image 985
Callirye Avatar asked Feb 21 '23 16:02

Callirye


1 Answers

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]))),
like image 61
Niklas B. Avatar answered Mar 04 '23 23:03

Niklas B.