简体   繁体   English

Python - 如何对列表中包含数字的字符串进行排序

[英]Python - How to sort strings with numbers inside of them in a list

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.我如何按顺序对这些进行排序,以便打印出来。

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: Output:

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

You can use a key function that, for each string, returns a tuple of the form (score_as_integer, name_as_string) .您可以使用键 function,对于每个字符串,返回一个形式为(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)

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!我希望这会有所帮助,如果没有,请道歉!

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 Output

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

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

gives

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

Quite neat相当整洁

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM