Python 如何根据子列表的长度对列表列表进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30346356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:18:24  来源:igfitidea点击:

How to sort list of lists according to length of sublists

pythonlistpython-2.7

提问by rajeshv90

I have the following list

我有以下清单

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

采纳答案by Alik

Use keyparameter available in sortand sorted. It specifies a function of one argument that is used to extract a comparison key from each list element

使用和 中key可用的参数。它指定了一个参数的函数,用于从每个列表元素中提取比较键sortsorted

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

回答by sachin saxena

can be done by

可以通过

sorted(a, key=len)