如何按内部列表的特定索引对列表列表进行排序? [英] How to sort a list of lists by a specific index of the inner list?

查看:27
本文介绍了如何按内部列表的特定索引对列表列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一份清单.例如,

<预><代码>[[0,1,'f'],[4,2,'t'],[9,4,'afsd']]

如果我想通过内部列表的字符串字段对外部列表进行排序,你会如何在 python 中做到这一点?

解决方案

这是itemgetter

<预><代码>>>>from 操作符导入 itemgetter>>>L=[[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]>>>排序(L,键=itemgetter(2))[[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]

这里也可以使用 lambda 函数,但是在这种简单的情况下 lambda 函数速度较慢

I have a list of lists. For example,

[
[0,1,'f'],
[4,2,'t'],
[9,4,'afsd']
]

If I wanted to sort the outer list by the string field of the inner lists, how would you do that in python?

解决方案

This is a job for itemgetter

>>> from operator import itemgetter
>>> L=[[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
>>> sorted(L, key=itemgetter(2))
[[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]

It is also possible to use a lambda function here, however the lambda function is slower in this simple case

这篇关于如何按内部列表的特定索引对列表列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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