如何根据子列表的长度对列表列表进行排序 [英] How to sort list of lists according to length of sublists
本文介绍了如何根据子列表的长度对列表列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下列表
a = [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h'], ['i', 'j', 'k', 'l'], ['m', 'n'], ['o']]
我想根据其子列表的长度对列表进行排序. 结果应为:
I would like to sort the list based on the length of their sub lists. The result should be like:
a = [['o'],['d','e'],['m', 'n'],['a', 'b', 'c'],['f', 'g', 'h'], ['i','j','k','l']]
推荐答案
使用sort
和sorted
中可用的key
参数.它指定一个参数的功能,该参数用于从每个列表元素中提取比较键
Use key
parameter available in sort
and sorted
. It specifies a function of one argument that is used to extract a comparison key from each list element
In [6]: a = [['a', 'b', 'c'], ['d', 'e'], ['f', 'g', 'h'], ['i', 'j', 'k', 'l'], ['m', 'n'], ['o']]
In [7]: a.sort(key=len)
In [8]: print a
[['o'], ['d', 'e'], ['m', 'n'], ['a', 'b', 'c'], ['f', 'g', 'h'], ['i', 'j', 'k', 'l']]
这篇关于如何根据子列表的长度对列表列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文