we have 3 lists in below
JavaScript
x
5
1
[2,3,4]
2
[5,6,7]
3
[8,9,10]
4
5
so , how we can sum all of similar index in lists together? i mean is 2 and 5 and 8 be sum together & 3 and 6 and 9 also be sum together & 4 and 7 and 10 as well ? but just use lambda and map…
actually i have no idea for that and this code is just for sending this question
JavaScript
1
10
10
1
x=[
2
[5,8,1],
3
[9,4,7],
4
[2,6,3],
5
]
6
7
8
print(list(map(lambda x : x[1], x)))
9
10
Advertisement
Answer
to get them all together use zip
:
JavaScript
1
2
1
new = list((zip(*matrix)))
2
output:
JavaScript
1
2
1
[(2, 5, 8), (3, 6, 9), (4, 7, 10)]
2
to sum them up you can use sum
and map
:
JavaScript
1
2
1
sum = list(map(sum, zip(*matrix)))
2
output:
JavaScript
1
2
1
[15, 18, 21]
2