I am finding a way to calculate the difference of values from one 2-dimensional array.
arr1 = [[1,2,3],[5,6,7]]
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()
.
>>> arr1 = [[1,2,3], [5,6,7]] >>> [b - a for (a, b) in zip(*arr1)] [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]]
.)