I am trying to make a leaderboard. Here is a list i have :
list=['rami4\n', 'kev13\n', 'demian6\n']
I would like to be able to sort this list from highest number to smallest, or even smallest to highest, giving something like :
list=['kev13\n', 'demian6\n', 'rami4\n']
I tried to use stuff like re.findall('\d+', list[loop])[0]
but i only managed to get, out of the list, the best player. Not wanting to repeat the code for as many players as there are, does anyone have an idea ?
You indeed have to use the re
module, but also the key
parameter of the sort()
method.
reg = re.compile('\w*?(\d+)\\n')
lst.sort(key=lambda s: int(reg.match(s).group(1)))
It works fine using findall()
as you did too:
reg = re.compile('\d+')
lst.sort(key=lambda s: int(reg.findall(s)[0]))
Note that I compile()
the regular expression so it is computed once and for all rather than for each element in the list.