在Python中以数字方式对列表进行排序 [英] Sort a list numerically in Python

查看:508
本文介绍了在Python中以数字方式对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有此列表,我们将其称为listA.我正在尝试在每个列表中获取[3]项目,例如['5.01','5.88','2.10','9.45','17.58','2.76']按排序顺序.因此,最终结果将重新开始整个列表,其中圣诞老人位于顶部.那有意义吗?

So I have this list, we'll call it listA. I'm trying to get the [3] item in each list e.g. ['5.01','5.88','2.10','9.45','17.58','2.76'] in sorted order. So the end result would start the entire list over again with Santa at the top. Does that make any sense?

[['John Doe', u'25.78', u'20.77', '5.01'], ['Jane Doe', u'21.08', u'15.20', '5.88'], ['James Bond', u'20.57', u'18.47', '2.10'], ['Michael Jordan', u'28.50', u'19.05', '9.45'], ['Santa', u'31.13', u'13.55', '17.58'], ['Easter Bunny', u'17.20', u'14.44', '2.76']]

推荐答案

如果要按排序顺序返回完整列表,则可以使用.这将获取您的输入列表,并在其顶部运行sorted.设置为Truereverse参数以相反的顺序(降序)对列表进行排序,而key参数指定了进行排序的方法,在这种情况下,该方法是每个列表的第三个参数的float :

If you want to return the complete list in sorted order, this may work. This takes your input list and runs sorted on top of it. The reverse argument set to True sorts the list in reverse (descending) order, and the key argument specifies the method by which to sort, which in this case is the float of the third argument of each list:

In [5]: l = [['John Doe', u'25.78', u'20.77', '5.01'] # continues...    
In [6]: sorted(l, reverse=True, key=lambda x: float(x[3]))
Out[6]:
[['Santa', u'31.13', u'13.55', '17.58'],
 ['Michael Jordan', u'28.50', u'19.05', '9.45'],
 ['Jane Doe', u'21.08', u'15.20', '5.88'],
 ['John Doe', u'25.78', u'20.77', '5.01'],
 ['Easter Bunny', u'17.20', u'14.44', '2.76'],
 ['James Bond', u'20.57', u'18.47', '2.10']]

如果您只需要按排序顺序排列的值,则其他答案将为您提供可行的方法.

If you only need the values in sorted order, the other answers provide viable ways of doing so.

这篇关于在Python中以数字方式对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆