Python - sort a list of nested lists

爱⌒轻易说出口 提交于 2019-12-09 14:32:43

问题


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?


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



回答2:


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



回答3:


l.sort(key=sum_nested)

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


来源:https://stackoverflow.com/questions/280222/python-sort-a-list-of-nested-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!