Python - sort a list of nested lists

*爱你&永不变心* 提交于 2019-12-04 00:19:05
Alex Coventry

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

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