Search code examples
pythonlistsorting

How to sort a list of lists of lists by the total number of items?


I have a list:

[
  [['4', '10'], ['2', '6'], ['1', '3']],
  [['1', '4', '10'], ['5', '2', '6'], ['11', '1', '3']]
]

I want to sort by the total number of items. The first group has the item 4, 10, 2, 6, 1 and 3, in total, 6 item. The second has 1, 4, 10, 5, 2, 6, 11, 1 and 3, in total, 9 elements. So I want the second group to come before the first one:

[
  [['1', '4', '10'], ['5', '2', '6'], ['11', '1', '3']],
  [['4', '10'], ['2', '6'], ['1', '3']]
]

(the list has lots more groups, this is just a shoter version of the problem)

I tried to do a sort(key=len) but it sorted by the number of lists each group has (like, the first group has 3 lists, the second has also 3).


Solution

  • From what I understand, you want to sort based on the sum of lengths of all lists contained in each list. You can use both sum and len (as well as map for combining them) to achieve your goal:

    ls = [
      [['4', '10'], ['2', '6'], ['1', '3']],
      [['1', '4', '10'], ['5', '2', '6'], ['11', '1', '3']]
    ]
    
    sorted_ls = sorted(ls, key=lambda l: sum(map(len, l)), reverse=True)
    

    Do note that sorted will return the list sorted in ascending order, so we pass reverse=True to sort it in descending order.