0
scores = []
with open("scores.txt") as f:
    for line in f:
        name, score = line.split(',')
        score = int(score)
        scores.append((name, score))
        scores.sort(key=lambda s: s[1])
for name, score in scores:
    print(name + ", " + str(score))

This code can be used to show a txt file looking like this (disordered):

alpha, 3
beta, 1
gamma, 2

To looking like this:

beta, 1
gamma, 2
alpha, 3

How can I modify the code so that it instead prints as:

alpha, 3
gamma, 2
beta, 1 
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
yuyu
  • 21
  • 1
  • 3

3 Answers3

2

Use the reverse argument to list.sort():

scores.sort(key=lambda s: s[1], reverse=True)

From the documentation:

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
2

Just use scores[::-1] instead of scores in the last for-loop. Here's a small illustration of this behaviour:

a=list(range(10))
print(a[::-1])
jadsq
  • 3,033
  • 3
  • 20
  • 32
0

Use reverse when you sort:

>>> l  = [('a', 1), ('c',5), ('a', 2), ('b', 1)]
>>> l.sort(key=lambda i: i[1], reverse=True)
>>> l
[('c', 5), ('a', 2), ('a', 1), ('b', 1)]

You can use it with sorted:

>>> l  = [('a', 1), ('c',5), ('a', 2), ('b', 1)]
>>> sorted(l, key=lambda i: i[1], reverse=True)
[('c', 5), ('a', 2), ('a', 1), ('b', 1)]
>>> 
Kenly
  • 24,317
  • 7
  • 44
  • 60