Sai nadupalli Sai nadupalli - 3 months ago 19
Python Question

Sorting based on max length and max sum

Can you please help me figure this out

q = [[12, 13, 14], [8, 9, 10,11], [2, 3, 4], [5, 6, 7]]


suppose I've a list like q, How do I sort the based on


  1. Max length of sublists and

  2. Max sum of the sublists



The output should be:

q = [[8,9,10,11],[12,13,14][5,6,7],[1,2,3]]

Jim Jim
Answer

Supply your criteria in a lambda function for the key:

sorted(q, key=lambda sub: (len(sub), sum(sub)), reverse=True)
>>> [[8, 9, 10, 11], [12, 13, 14], [5, 6, 7], [2, 3, 4]]

The lambda function will take every sub-list x and sort it based on it's len, in cases where the result of len is not sufficient in making a decision, the sum of their contents is used to break the tie.

Comments