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:
我想根据嵌套列表中所有数字的总和对此列表进行排序...因此,我想要按l排序的值将如下所示:
[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?
这样做有什么好的pythonic方式?
3 个解决方案
#1
16
A slight simplification and generalization to the answers provided so far, using a recent addition to python's syntax:
对目前为止提供的答案进行了略微简化和概括,使用了最近添加的python语法:
>>> 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
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
#3
5
l.sort(key=sum_nested)
Where sum_nested()
is:
sum_nested()的位置是:
def sum_nested(astruct):
try: return sum(map(sum_nested, astruct))
except TypeError:
return astruct
assert sum_nested([[([8, 9], 10), 11], 12]) == 50
#1
16
A slight simplification and generalization to the answers provided so far, using a recent addition to python's syntax:
对目前为止提供的答案进行了略微简化和概括,使用了最近添加的python语法:
>>> 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
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
#3
5
l.sort(key=sum_nested)
Where sum_nested()
is:
sum_nested()的位置是:
def sum_nested(astruct):
try: return sum(map(sum_nested, astruct))
except TypeError:
return astruct
assert sum_nested([[([8, 9], 10), 11], 12]) == 50