Python - sort a list of nested lists

Claudiu picture Claudiu · Nov 11, 2008 · Viewed 8.1k times · Source

I have input consisting of a list of nested lists like this:

l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]

I want to sort this list based on the sum of all the numbers in the nested lists... so, the values I want to sort by of l would look like this:

[39, 6, 13, 50]

Then I want to sort based on these. So the output should be:

[[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]]

What's a nice pythonic way of doing this?

Answer

Alex Coventry picture Alex Coventry · Nov 11, 2008

A slight simplification and generalization to the answers provided so far, using a recent addition to python's syntax:

>>> l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]
>>> def asum(t): return sum(map(asum, t)) if hasattr(t, '__iter__') else t
...
>>> sorted(l, key=asum)
[[1, 2, 3], [4, [5, 3], 1], [[[[39]]]], [[[[8, 9], 10], 11], 12]]