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

编程入门 行业动态 更新时间:2024-10-09 19:14:52
本文介绍了如何根据子列表中的值对列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

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

本文发布于:2023-11-29 09:01:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645943.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!