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?

Asked by: Oliver632 | Posted: 05-10-2021

Answer 1

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]]

Answered by: Chester468 | Posted: 06-11-2021

Answer 2

A little recursive function would do it:

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

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

Answered by: Arnold956 | Posted: 06-11-2021

Answer 3


Where sum_nested() is:

def sum_nested(astruct):
    try: return sum(map(sum_nested, astruct))
    except TypeError:
        return astruct

assert sum_nested([[([8, 9], 10), 11], 12]) == 50

Answered by: John275 | Posted: 06-11-2021

Similar questions

Python nested lists

This question already has answers here:

Python - find all lists in a nested list

I am working on my own implementation of genetic programming (GP) in Python. GP aims at evolving programs, represented as LISP S-expressions, to search for a good solution to a problem. S-expressions use prefix notation. For instance: (+ (- 1 2) (- 3 (/ 4 5))) This expression is equivalent to the following in infix algebra. (1 - 2) + (3 - 4 / 5) I ...

Python join two nested lists

I have two nested lists of strings: listA = [["SomeString1", "A", "1"], ["SomeString2", "A", "2"], ["SomeString3", "B", "1"], ["SomeString4", "B", "2"]] listB = [["OtherString1", "A", "1"], ["OtherString2", "A", "2"], ["OtherString3", "B", "1"], ["OtherString4", "B", "2"]] For every list in A, I want to find the list in B where ...

Python - Nested Lists

I'm trying to cross check two nested list values, and if I get a match, append the values from list1 into list2. For example; list1 = [[ip, hostname], [ip, hostname], [ip, hostname]] list2 = [[ip, ip_upper, type, hostname, location], [ip, ip_upper, type, hostname, location], [ip, ip_upper, type, hostname, location]] I want to check if the value in list1[x][0] is in

python - How do I get such a nested lists?

variable tree structure - nestedList1 variable aa3 | aa1 aa2 bb1 \ / / aa bb \ / root - nestedList2 variable bb4 | aa3 bb2 bb3 | \ / aa1 aa2 bb1 cc1 \ / / | aa bb cc \ | / root

python - Sum of two nested lists

I have two nested lists: a = [[1, 1, 1], [1, 1, 1]] b = [[2, 2, 2], [2, 2, 2]] I want to make: c = [[3, 3, 3], [3, 3, 3]] I have been referencing the zip documentation, and researching other posts, but don't really understand how they work. Any help would be greatly appreciated!

python - Find an item in nested lists

A project in a coding class I'm taking asks students to finish the code for a password saver with a number of options and a menu. The part I'm having difficulty with is printing a password based on the website associated with it. Passwords are saved in a list like so: passwords = [["yahoo","XqffoZeo"],["google","CoIushujSetu"]] What I'm attempting to do is find the address of an it...

Python Nested Lists help please

Closed. This question needs to be more focused. It ...

Python pass by value with nested lists?

I'm having a simple issue that's frustrating me. I'm sure I'm making a very obvious mistake, but I can't seem to find it. I want l_old to be the copy of l before undergoing iteration. I have the following Python script. import random def runtest(n,steps): l=[] for i in range(n): sublist=[] for j in range(n): sublist.append(0) l.append(su...

Python min value in nested lists

Closed. This question needs to be more focused. It ...

From python to R: Nested lists

I have spatial coordinate data from python which looks something like this: [[179.0, -79.0], [127.0, 301.0], [-92.0, 310.0]] I am analyzing this data in R, but I don't know how to grab individual coordinates i.e. how to get to [179.0, -79.0]. I have tried different indexing options but had no luck. Just for context, my dataframe has a column with python list of lists. ...

Python another nested lists

Take the sub list each and divide that list into another sub list by searching for particular word in the list. Here is my code: for i in list_1: for x in i: regex = re.compile(r '^pft') matched = filter( ,x) print(matched) list_1 = [['MP1 Z A VDD VNW pft\n', 'MN1 Z A VSS VPW nft\n'], ['MM19 Z A VDD VNW pft\n', 'MM18 Z A VDD VNW pft\n', 'MM17 Z A VDD VNW pft...

python - How to make nested lists out of flat list?

Need to turn this example list list = ["Hello","world","!!!"] Into nested lists like this new_list = ["Hello",["world",["!!!",None]]] For any kind of flat list given . Somehow I can make a flat list out of nested lists , but after hours of trying I can't seem to find the solution by myself or by googling . I've searched here but nothing comes out for this ...

Python sort nested lists

I have these lists which I have sorted in ascending order via selection sorting but it only applies to index [0]. How would I append it so it sorts the next index as well? The result that I am after is : [[2, 3], [4, 5], [6, 7]] So far i have: def selection_sort(list_a): indexing_length = range (0, len(list_a)-1) for i in indexing_length: min_value = i ...

python - How to index into nested lists?

I want to make a function in python which receives as arguments a matrix, a coordinate for the line and another coordinate for the column. For example: A matrix m=[[1,2,3], [4,5,6]] and the function will receive the arguments (m,0,0) It should return 1 (Which is the number located in position 0,0 in the matrix).

python - How can I find all lists in a nested list that contains the user input

I have a nested list and trying to use a list comprehension to create a new nested list which contains all lists that contain the year inputted by the user nested_list = [['2021','France'],['2021','Germany'],['2021','Ireland'],['2020','Turkey'],['2020','Germany'],['2020','Ireland'],['2019','Japan'],['2019','USA'],['2019','Ireland']] When the user input a year (2021), I want the output to be ...

python - How to sum up two different nested lists?

list_a = [[[1.1, 2.2], [3.3, 4.4]], [[5.5, 6.6], [7.7, 8.8]]] list_b = [[1.1, 2.2], [3.3, 4.4]] I just want to sum the list [[1.1, 2.2], [3.3, 4.4]] in the list_a with the list [1.1, 2.2] in list_b For example: 1.1+1.1, 2.2+1.1 then 3.3+2.2, 4.4+2.2. After that the output will store back to an empt...

python - Sort nested lists by list

How can I efficiently sort nested lists by the first element of each nested list matching the order given in order list? List: [[97, 2, 0, 2], [97, 2, 0, 2], [98, 1, 2, 3], [99, 3, 3, 6], [99, 3, 3, 6], [99, 3, 3, 6], [101, 1, 6, 7], [100, 1, 7, 8]] Order list: [97, 98, 99, 99, 101, 100, 97, 99] Desired list: [[97, 2, 0, 2], [98, 1, 2, 3], [99, 3, 3, 6], [99, 3, 3, 6], [...

python - How can we add two different nested lists together?

This question already has answers here:

python - Get value from key within nested Lists of Dicts

I am fairly new to Python and have been working on trying to print out the values attached to a key which is present in a nested list of dictionaries in a JSON. Here is the structure from what I can tell: details - List of dicts scorecardDetails - List of dicts scorecard - Dict playerHandicap - Key:Value

python - need to put a nested Dict into a text file

I have a nested dict like this d={ time1 : column1 : {data1,data2,data3} column2 : {data1,data2,data3} column3 : {data1,data2,data3} #So on. time2 : {column1: } #Same as Above } data1,data2,data3 represent the type of data and not the data itself I need to put this dict into a file like this. Timestamp col1/data1 Col1/data2 col1/data3...

python - How to do nested Django SELECT?

class Friendship(models.Model): from_friend = models.ForeignKey(User, related_name='friend_set') to_friend = models.ForeignKey(User, related_name='to_friend_set') I'd like to SELECT all to_friends that have from_friend = a certain User. Then, I'd like to pass to_friends to inside filter in another .objects.filter(). Is this the way to do it? Thanks!

python - nested for loop

Just learning Python and trying to do a nested for loop. What I'd like to do in the end is place a bunch of email addresses in a file and have this script find the info, like the sending IP of mail ID. For now i'm testing it on my /var/log/auth.log file Here is my code so far: #!/usr/bin/python # this section puts emails from file(SpamEmail) in to a array(array) in_file = open("testFile", "r") arr...

python - Split a list into nested lists on a value

Say I have a list like so: [1, 4, None, 6, 9, None, 3, 9, 4] I decide to split this into nested lists on None, to get this: [[1, 4], [6, 9], [3, 9, 4]] Of course, I could have wanted to do this on (9, None) in which case, we would have got: [[1, 4], [6], [3], [4]] This is trivial to do using list ...

bash - Python nested loop from files

I have the following code: inputActionFile = '../action.txt' inputDaerahFile = '../daerah.txt' inputStuffFile = '../stuff.txt' inputTermsFile = '../terms.txt' outputFile = 'hasil.out' inputAction = open(inputActionFile, 'r') inputDaerah = open(inputDaerahFile, 'r') inputStuff = open(inputStuffFile, 'r') inputTerms = open(inputTermsFile, 'r') output = open(outputFile, 'w') for actionLine in inputAction: ...

python - Sort list by nested tuple values

Is there a better way to sort a list by a nested tuple values than writing an itemgetter alternative that extracts the nested tuple value: def deep_get(*idx): def g(t): for i in idx: t = t[i] return t return g >>> l = [((2,1), 1),((1,3), 1),((3,6), 1),((4,5), 2)] >>> sorted(l, key=deep_get(0,0)) [((1, 3), 1), ((2, 1), 1), ((3, 6), 1), ((4, 5), 2)] >>> sorted(l, ke...

python - Nested list to string

I have a list of instances of class Test. This class have method like name and parent [Test('a', ''), Test('b', ''), Test('c', 'a'), Test('d', 'a'), Test('e', 'c')] First argument is name, second parent. Parent arg is simply a arg name of parent class. I want convert this list to string like: Test('a', '') |-- Test('c', 'a') ...

python - Nested for loop to search 2 lists

Using: Python 2.4 Currently, I have a nested for loop that iterates over 2 lists and makes a match based on two elements that exists on both lists. Once a match has been found, it the element from the r120Final list and puts in a new list called "r120Delta": for r120item in r120Final: for spectraItem in spectraFinal: if(str(spectraItem[0]) == r120item[2].strip()) and (str(spectraItem[25]) =...

How do i speed up a python nested loop?

I'm trying to calculate the gravity effect of a buried object by calculating the effect on each side of the body then summing up the contributions to get one measurement at one station, an repeating for a number of stations. the code is as follows( the body is a square and the code calculates clockwise around it, that's why it goes from -x back to -x coordinates) grav = [] x=si.arange(-30.0,30.0,0.5) #-9....

Python nested loop

Hello I am new to python and have a question about the best/pythonic way to do nested loops. I want to go put each directory in an array with a nested array of the file contained in a that directory. I have been looking at pythons arrays, dicts, sets and tupples and not sure of the best way to do this [ Note I just want to do this for one level not recursively through all directories ] Curr...

python - What's the best Django search app?

How can I use a DLL file from Python?

What is the easiest way to use a DLL file from within Python? Specifically, how can this be done without writing any additional wrapper C++ code to expose the functionality to Python? Native Python functionality is strongly preferred over using a third-party library.

python - PubSub lib for c#

Is there a c# library which provides similar functionality to the Python PubSub library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.

python - What is the best way to copy a list?

This question already has answers here:

python - Possible Google Riddle?

My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. t-shirt So, I have a couple of guesses as to what it means, but I was just wondering if there is something more. My first guess is that eac...

How do you check whether a python method is bound or not?

Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?

ssh - How to scp in Python?

What's the most pythonic way to scp a file in Python? The only route I'm aware of is os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) which is a hack, and which doesn't work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host. I'm aware of Twisted'...

python - How do I create a new signal in pygtk

I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.

python - What do I need to import to gain access to my models?

I'd like to run a script to populate my database. I'd like to access it through the Django database API. The only problem is that I don't know what I would need to import to gain access to this. How can this be achieved?

python - How do I edit and delete data in Django?

I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), EDIT it and save it back to the DB. Secondly how do I DELETE the data that's in the DB? i.e. search, select and then delete! Please show me an example of the code ...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python