python sum the values of lists of list

2019-01-12 04:45发布

I have list of lists and i need to sum the inner lists, for example,

a = [[1,2,3], [2,1,4], [4,3,6]]

for my case, the len of a[i] is same, that is all the inner lists have same dimension.

and i need the output as

result = [6,7,13]

what i did is:

result = [sum(a[i]) for i in range(len(a))]

Since my len(a) is very high, i hope there will be a alternative way to get the result without using the for loop.

标签: python list sum
3条回答
欢心
2楼-- · 2019-01-12 05:03
result = map(sum, a)

Is the way I would do it. Alternatively:

result = [sum(b) for b in a]

The second variation is the same as yours, except it avoids the unnecessary range statement. In Python, you can iterate over lists directly without having to keep a separate variable as an index.

查看更多
等我变得足够好
3楼-- · 2019-01-12 05:05

A simple answer.

a = [[1,2,3], [2,1,4], [4,3,6]]
result = [sum(l) for l in a]

result
[6, 7, 13]
查看更多
ら.Afraid
4楼-- · 2019-01-12 05:10

I know that no one like it but just to give an option:

result = [reduce(lambda x, y: x+y, l) for l in a]
查看更多
登录 后发表回答