Home > Net >  Python - How to sort strings with numbers inside of them in a list
Python - How to sort strings with numbers inside of them in a list

Time:04-08

I need to sort the highscores of my game in order from highest to lowest but I also want the name next to it so it is still a string.

This is my list

highscores = ["Herbert 99999", "Bob 543", "Jerry 35", "Fred 325", "Tom 972"]

How do I sort these in order so I can print them out.

CodePudding user response:

I think you would be a lot better off using a dictionary

highscores = {"Herbert": 99999, "Bob": 534, "Jerry":35}

Then you could just sort the dictionary by the values

dict(sorted(highscores.items(), key =lambda highscore: highscore[1], reverse=True))

Using a dictionary would also probably make your code more efficient. I hope this helps, apologies if it doesn't!

CodePudding user response:

highscores = ["Herbert 99999", "Bob 543", "Jerry 35", "Fred 325", "Tom 972"]

# temporary list of ordered pairs
tmp = sorted(map(str.split, highscores), key=lambda pair: int(pair[1]), reverse=True)

# marge each pair to get a list of strings
ordered_highscores = list(map(' '.join, tmp))

print(ordered_highscores)

Output

['Herbert 99999', 'Tom 972', 'Bob 543', 'Fred 325', 'Jerry 35']

CodePudding user response:

highscores.sort(key=lambda x:int(x.split()[-1]))

gives

['Jerry 35', 'Fred 325', 'Bob 543', 'Tom 972', 'Herbert 99999']

Quite neat

CodePudding user response:

You can use a key function that, for each string, returns a tuple of the form (score_as_integer, name_as_string). That way, ties will be sorted by name.

def by_score(item):
   name, score = item.rsplit(maxsplit=1)
   return -int(score), name.lower()

highscores.sort(key=by_score)

CodePudding user response:

If you want the high score at the start of your list then:

highscores = ["Herbert 99999", "Bob 543", "Jerry 35", "Fred 325", "Tom 972"]
highscores.sort(key=lambda x: int(x.split()[-1]), reverse=True)
print(highscores)

Output:

['Herbert 99999', 'Tom 972', 'Bob 543', 'Fred 325', 'Jerry 35']
  • Related