Home > front end >  How can I sort scores in a leaderboard?
How can I sort scores in a leaderboard?

Time:09-23

I've been trying to sort a top-5 leaderboard which includes the score and the username of the account that got the score. Here is my current code:

g = open("scores.txt", "r")
score1 = g.readline().strip()
score2 = g.readline().strip()
score3 = g.readline().strip()
score4 = g.readline().strip()
score5 = g.readline().strip()
print(score1,score2,score3,score4,score5)
print(sorted([score1,score2,score3,score4,score5], reverse = True))
g.close()

It seems to work, but it only sorts the leftmost digits of the scores, for example it sorts 100coolguy 50otherguy 10coolguy 2000coolguy 2otherguy as 50otherguy 2otherguy 2000coolguy 10coolguy 100coolguy.

A list of the scores, and how they should be formatted afterwards:

100otherexample 50example 10otherexample 2000example 2example
2000example 100otherexample 50example 10otherexample 2example

CodePudding user response:

from natsort import natsorted
print(natsorted([score1,score2,score3,score4,score5], reverse = True))

CodePudding user response:

You can first find digits then sort base digits like below:

st = ['100coolguy' , '50otherguy' , '10coolguy' , '2000coolguy' ,'2otherguy']

def find_int(text):
    return int(''.join(t for t in text if t.isdigit()))


st.sort(key=find_int, reverse=True)
print(st)

Output:

['2000coolguy', '100coolguy', '50otherguy', '10coolguy', '2otherguy']

CodePudding user response:

You need give a custom key to sorted key is what is evaluated instead of the whole list item in the sorting process:

A regex implementation:

import re

l = ["100coolguy", "50otherguy", "10coolguy", "2000coolguy", "2otherguy"]

def my_key(item):
    item_split = re.split("[a-z]", item, 1, flags=re.I)
    return int(item_split[0])

l_sorted = [sorted(l, key=my_key, reverse=True)]
print(l_sorted)

Splits at any character ("[a-z]") for 1 time and ignores case with re.I.

https://docs.python.org/3/howto/sorting.html#key-functions

  • Related