Python summarizes list list values

I have a list of lists and I need to summarize internal lists, e.g.

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

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

and I need a conclusion like

 result = [6,7,13] 

What I've done:

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

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

+4
source share
3 answers
 result = map(sum, a) 

I would do that. As an alternative:

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

The second option is the same as yours, except that it avoids the unnecessary range operator. In Python, you can iterate over lists directly without storing a separate variable as an index.

+18
source

I know that no one likes this, but just gives the opportunity:

 result = [reduce(lambda x, y: x+y, l) for l in a] 
+3
source

Simple answer.

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

Source: https://habr.com/ru/post/1444735/


All Articles