Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort list of lists according to length of sublists [duplicate]

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']] 
like image 975
rajeshv90 Avatar asked May 20 '15 09:05

rajeshv90


People also ask

How do you sort a list of lists based on length?

Sort the list by passing key to the sort(key = len) method of the list. We have to pass len as key for the sort() method as we are sorting the list based on the length of the string. sort() method will sort the list in place.

How do I sort a list of sublists in Python?

You can custom the sort behaviour by pass a key and reverse. sorted will return a new list. If in-place sort wanted, use list. sort .

How do I sort a list by second element in sublist?

1. Take in a list containing sublists. 2. Using two for loops, use bubble sort to sort the sublists based on the second value of the sublist.


1 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']] 
like image 155
Alik Avatar answered Sep 29 '22 11:09

Alik