2

This 2 dimensional list contains name and score. I need it to sort in descending value from the 2nd column.

scores = "scores.txt"
highScores = list()   # place all your processed lines in here

with open(scores) as fin:
    for line in fin:
       lineParts = line.split(": ")
       if len(lineParts) > 1:
           lineParts[-1] = lineParts[-1].replace("\n", "")
           highScores.append(lineParts)   # sorting uses lists
    highScores.sort(key = lambda x: x[1], reverse = True)
print(highScores)

with open('sorted.txt', 'w') as f:
    for item in highScores:
        f.write(str(item) +"\n")

The inputs are:

test1: 5
test2: 6
test3: 1
test4: 2
gd: 0
hfh: 5
hr: 3
test: 0
rhyddh: 0
Marty: 5425
testet: 425
place: 84
to: 41

But the outputs are:

['place', '84']
['test2', '6']
['Marty', '5425']
['test1', '5']
['hfh', '5']
['testet', '425']
['to', '41']
['hr', '3']
['test4', '2']
['test3', '1']
['gd', '0']
['test', '0']
['rhyddh', '0']

As seen, it sorts the column only by the first digit. How can I fix this?

idjaw
  • 25,487
  • 7
  • 64
  • 83
Marty
  • 21
  • 1
  • That is because you are sorting integers that are of type string and you aren't actually sorting by type int. Change the second item to `int` explicitly then sort. – idjaw Jun 14 '18 at 00:34
  • and https://stackoverflow.com/questions/32631581/python-how-do-i-sort-integers-in-a-text-file-into-ascending-and-or-descending-o – idjaw Jun 14 '18 at 00:38

1 Answers1

1

You need to convert strings to integers in your sort key:

highScores.sort(key=lambda x: int(x[1]), reverse=True)

Otherwise, as you found, your sort will be processed one character at a time, as you would expect with a string.

jpp
  • 159,742
  • 34
  • 281
  • 339