[英]How do I sort this python list by the number?
I am trying to sort a number of people based on their score, and then print out the top 3 people and their scores. 我试图根据他们的分数对一些人进行排序,然后打印出前三名的人和他们的分数。 Right now it looks like this:
现在看起来像这样:
List = ['A 3.0', 'B 4.0', 'C 13.0'] #My list
Sorted = sorted(List, key = lambda item:item.split(" ")[1], reverse = True) #Sorting script
print("Top three scorers and their average goal scores.", "\n", Sorted[0], "\n", Sorted[1], "\n", Sorted[2]) #Printing function
But when I run it, it prints this: 但是当我运行它时,它会打印出:
B 4.0
A 3.0
C 13.0
But '13.0' is not at all smaller than '3.0' and '4.0'. 但是“ 13.0”一点也不小于“ 3.0”和“ 4.0”。 I want the actual highest number to be at the top, does anyone have the answer, I am using 'python 3.4.4'.
我希望实际的最高数字在顶部,有人回答吗?我正在使用“ python 3.4.4”。
I am thinking that it might be sorting by the '1' and then by the '3' in the '13.0' as if separate characters, but I don't know how to fix it. 我认为它可能是按'1'排序,然后按'13 .0'中的'3'排序,好像是单独的字符一样,但是我不知道如何解决。
更改第二行,如下所示。(拆分项是一个字符串。将其转换为浮点数,它将起作用。)
Sorted = sorted(List, key = lambda item:float(item.split(" ")[1]), reverse = True) #Sorting script
只需将其转换为float以具有如下数字顺序:
Sorted = sorted(List, key = lambda item:float(item.split(" ")[1]), reverse = True) #Sorting script
If you are not specific about using lists,I suggest you to do create an object/tuple of something similar to the below 如果您不确定使用列表,建议您创建一个类似于以下内容的对象/元组
new_tuple= [('A', 3.0),('B', 4.0),('C', 13.0)]#create an object
Sorted = sorted(tuple, key = lambda new:new[1], reverse = True) #Sorting script
print("Top three scorers and their average goal scores.", "\n", Sorted[0], "\n", Sorted[1], "\n", Sorted[2]) #Printing function
Hope this helps.All the best :) 希望这会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.