-2

I need to somehow change this piece of code from outputting from Smallest -> Highest, to Highest -> Smallest.

Code:

scores = []
with open("scoreboard.txt") as f:
    for line in f:
        name, score = line.split(',')
        score = int(score)
        scores.append((name, score))

scores.sort(key=lambda s: s[2])

for name, score in scores:
    print(name, score, sep=', ')

Text File Contents:

Ben, 12
Ben, 6
Ben, 3
Ben, 21
Ben, 1

How I want it to output:

Ben, 1
Ben, 3
Ben, 6
Ben, 12
Ben, 21
Ben Hams
  • 1
  • 1

2 Answers2

1

Use the 'reverse' keyword.

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

Or:

scores.sort(key=lambda s: -s[2])
decorator-factory
  • 2,733
  • 13
  • 25
0

You can use the reverse kwarg of the sort fonction. Set it to True will reverse your list.

YoLecomte
  • 111
  • 1
  • 4