Reputation: 166
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 ?
Upvotes: 1
Views: 54
Reputation: 173
I have an other solution based on Object Oriented Programming and the overriding of the __lt__
special methods of str
.
import re
class SpecialString(str):
def __lt__(self, other):
pattern=re.compile(r"\d+")
return int(pattern.search(str(self)).group(0)) < int(pattern.search(str(other)).group(0))
if __name__ == "__main__":
listing = ['rami4\n', 'kev13\n', 'demian6\n']
spe_list = [SpecialString(x) for x in listing]
spe_list.sort()
print(spe_list)
Which print to the standard output:
['rami4\n', 'demian6\n', 'kev13\n']
This method allows you to not rewrite the sort
function and use the built-in one (which is probably optimized). More over, since your strings may be thinked like "specialization of the str
class", the inheritance mecanism is very suitable because you keep all its properties but re-write its comparison mecanism.
Upvotes: 1
Reputation: 19617
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.
Upvotes: 3