简体   繁体   English

如何按编号对python列表进行排序?

[英]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.

相关问题 如何按 Python 中另一个列表的索引号对列表进行排序? - How do I sort a list by another list's index number in Python? 我如何在python中对列表进行排序 - how do I sort list in python 如何在 Python 中对压缩列表进行排序? - How do I sort a zipped list in Python? Python 3 List:如何根据数字和字母对[('NJ',81),('CA',81),('DC',52)]进行排序? - Python 3 List: How do I sort [('NJ', 81), ('CA', 81), ('DC', 52)] base on number and then letters? 如何使用字母和数字组合对嵌套的元组列表进行排序 - How do I sort nested list of tuples with letter and number combinations 如果有一个整数与字符串绑定最小数字,我如何对列表进行排序? - How do I sort a list if there is an integer tied to a string by the smallest number? 如何按照与 Python 中另一个列表相同的顺序对列表进行排序? - How do I sort a list in the same order as another list in Python? Python如何查找列表中是否有数字,而不是列表的最后一个数字? - Python How do I find if an number is in a list but is not last number of the list? 如何对我在Python 3.3中附加的列表进行排序 - How do I sort a list that I have appended to in Python 3.3 如何从列表中删除相同的项目并在Python中对其进行排序? - How do I remove identical items from a list and sort it in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM