Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - sort a list of nested lists

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?

like image 361
Claudiu Avatar asked Nov 11 '08 07:11

Claudiu


People also ask

Can you sort a list of lists in Python?

Python List sort() Method Syntax. The Python sort() method sorts the elements of a list in a given order, including ascending or descending orders. The method works in place, meaning that the changed list does not need to be reassigned in order to modify the list.

How do you sort a list by another list in Python?

Approach : Zip the two lists. Create a new, sorted list based on the zip using sorted(). Using a list comprehension extract the first elements of each pair from the sorted, zipped list.

How do you sort a multidimensional list in Python?

sort , sorted accept optional key parameter. key function is used to generate comparison key. >>> sorted(lst, key=lambda x: x[1], reverse=True) [['I', 219], ['A', 22], ['P', 14], ['V', 13], ['G', 10], ...] >>>


2 Answers

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]]
like image 50
Alex Coventry Avatar answered Oct 23 '22 02:10

Alex Coventry


A little recursive function would do it:

def asum(a):
    if isinstance(a, list):
        return sum(asum(x) for x in a)
    else:
        return a

l = [[[[[39]]]], [1, 2, 3], [4, [5, 3], 1], [[[[8, 9], 10], 11], 12]]
l.sort(key=asum)
print l
like image 42
Greg Hewgill Avatar answered Oct 23 '22 03:10

Greg Hewgill