Use zip to "combine" lists into single one, then sum elements for each index:
c_agent_0 = [10.0, 11.0, 12.0, 13.0, 14.0]
c_agent_1 = [1.1, 12.3, 14.2, 13.2, 14.3]
c_agent_2 = [1.4, 12.1, 14.5, 13.1, 14.2]
zipped_list = zip[c_agent_0, c_agent_1, c_agent_2]
print zipped_list
print [sum[item] for item in zipped_list]
prints
[[10.0, 1.1, 1.4], [11.0, 12.3, 12.1], [12.0, 14.2, 14.5], [13.0, 13.2, 13.1], [14.0, 14.3, 14.2]]
[12.5, 35.4, 40.7, 39.3, 42.5]
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
The list is an important container and used almost in every code of day-day programming as well as web-development, more it is used, more is the requirement to master it and hence knowledge of its operations is necessary. Given a list of lists, the program to suppose to return the sum as the final list.
Let’s see some of the methods to sum a list of list and return list.
Method # 1: Using Naive method
L
=
[[
1
,
2
,
3
],
[
4
,
5
,
6
],
[
7
,
8
,
9
]]
print
[
"Initial List - "
,
str
[L]]
res
=
list
[]
for
j
in
range
[
0
,
len
[L[
0
]]]:
tmp
=
0
for
i
in
range
[
0
,
len
[L]]:
tmp
=
tmp
+
L[i][j]
res.append[tmp]
print
[
"final list - "
,
str
[res]]
Output:
Initial List - [[1, 2, 3], [4, 5, 6], [7, 8, 9]] final list - [12, 15, 18]
Method #2: Using numpy array
A numpy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays.
import
numpy as np
List
=
np.array[[[
1
,
2
,
3
],
[
4
,
5
,
6
],
[
7
,
8
,
9
]]]
print
[
"Initial List - "
,
str
[
List
]]
res
=
np.
sum
[
List
,
0
]
print
[
"final list - "
,
str
[res]]
Output:
Initial List - [[1 2 3] [4 5 6] [7 8 9]] final list - [12 15 18]
Method #3: Using zip[]
and list comprehension
List
=
[[
1
,
2
,
3
],
[
4
,
5
,
6
],
[
7
,
8
,
9
]]
print
[
"Initial List - "
,
str
[
List
]]
res
=
[
sum
[i]
for
i
in
zip
[
*
List
]]
print
[
"final list - "
,
str
[res]]
Output:
Initial List - [[1, 2, 3], [4, 5, 6], [7, 8, 9]] final list - [12, 15, 18]