How to sort a list of nested lists based on the sum of all the numbers in the nested lists in Python

1 Answer

0 votes
def sum_the_nested(lst): 
    return sum(map(sum_the_nested, lst)) if hasattr(lst, '__iter__') else lst

lst = [[[[[[8]]]]], [1, 2, 3], [7, [9, 5], 0], [[90]], [[[[4, 5], 6], 19], 30]]


lst = sorted(lst, key=sum_the_nested)

print(last)


#      6           8             21                  64               90
# [[1, 2, 3], [[[[[8]]]]], [7, [9, 5], 0], [[[[4, 5], 6], 19], 30], [[90]]]


'''
run:

[[1, 2, 3], [[[[[8]]]]], [7, [9, 5], 0], [[[[4, 5], 6], 19], 30], [[90]]]

'''

 



answered Jun 24, 2024 by avibootz
edited Jun 24, 2024 by avibootz
...