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?