简体   繁体   中英

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'. I want the actual highest number to be at the top, does anyone have the answer, I am using '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.

更改第二行,如下所示。(拆分项是一个字符串。将其转换为浮点数,它将起作用。)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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