I am finding a way to calculate the difference of values from one 2-dimensional array.
JavaScript
x
2
1
arr1 = [[1,2,3],[5,6,7]]
2
My array will be like this and I want my code to subtract 5-1,6-2 and 7-3.
Is it possible to do that?
Advertisement
Answer
You could use zip()
.
JavaScript
1
4
1
>>> arr1 = [[1,2,3], [5,6,7]]
2
>>> [b - a for (a, b) in zip(*arr1)]
3
[4, 4, 4]
4
(zip(*x)
is an useful idiom in general to transpose an iterable of iterables, i.e. turn [[1, 2, 3], [5, 6, 7]]
to [[1, 5], [2, 6], [3, 7]]
.)