本文介绍了如何根据子列表中的值对列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个看起来像这样的列表:
So I have a list that looks something like this:
example = [['b',1],['b',2],['a',2]]它需要进行排序才能变成:
And it needs to be sorted to become:
example = [['b',1],['a',2],['b',2]]即按[1]位置中的数字进行数字排序.该程序需要识别两个相同的数字,然后按字母顺序对这些元素进行排序.
I.e. sorted numerically by the number in the [1] position. The program needs to recognise when there are two numbers that are the same, and then sort these elements alphabetically.
有什么想法吗?
以及如何对列表进行排序,以便首先打印出最高编号?
and how would I go about sorting the list so that the highest number is printed first?, i.e:
example = [['a',2],['b',2],['b',1]]推荐答案
这是一个巧妙的把戏
>>> example = [['b',1],['b',2],['a',2]] >>> sorted(example, key=sorted) [['b', 1], ['a', 2], ['b', 2]]尽管仅适用于Python2
Only works for Python2 though
有两种方法可以按从高到低的顺序对数字进行排序
There are two ways to sort by numbers from highest to lowest
>>> sorted(example, key=lambda x: (-x[1], x[0])) [['a', 2], ['b', 2], ['b', 1]]或
>>> from operator import itemgetter >>> sorted(sorted(example), key=itemgetter(1), reverse=True) [['a', 2], ['b', 2], ['b', 1]]更多推荐
如何根据子列表中的值对列表进行排序?
发布评论