Skip to content
Advertisement

Are there any ways to calculate the subtraction of values from one 2-dimensional arrays in python? [closed]

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]].)

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement