如何根据子列表中的值对列表进行排序?

如何根据子列表中的值对列表进行排序?

问题描述:

所以我有一个看起来像这样的列表:

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]]