我有一个变量堆栈:
stacks = [[1, 2, 3], [[4, 5, 6], [1, 2, 3]]]
由此我想创建另一个高度列表,其中每个高度是堆栈中每个堆栈的索引1处的元素的总和。在上面的示例中,高度为:
heights = [2, 7]
其中2是堆栈[0] [1],7是堆栈[1] [0] [1] +堆栈[1] [1] [1]。对不起,如果以前不清楚。如何使用列表推导,map和/
或reduce?
答案 0 :(得分:5)
假设stacks
完全如您所述:
>>> stacks = [[1, 2, 3], [[4, 5, 6], [1, 2, 3]]]
>>> wrapped = (s if isinstance(s[0], list) else [s] for s in stacks)
>>> total = [sum(x[1] for x in w) for w in wrapped]
>>> total
[2, 7]
如果stacks
的元素始终是列表列表,那将更自然,恕我直言:
>>> stacks = [[[1, 2, 3]], [[4, 5, 6], [1, 2, 3]]]
>>> total = [sum(x[1] for x in w) for w in stacks]
>>> total
[2, 7]