How to sort list of lists according to length of sublists
Question:
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']]
Answers:
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']]
can be done by
sorted(a, key=len)
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']]
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']]
can be done by
sorted(a, key=len)