Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to substract multidimensional array in Python?

I have this multidimensional array:

n = [[1], [2], [3], [4], [5], [6], [7, 10], [8], [9], [7, 10]]

I want to substract all of them with 1. So the result will be:

result = [[0], [1], [2], [3], [4], [5], [6, 9], [7], [8], [6, 9]]
like image 504
colintobing Avatar asked Apr 13 '14 02:04

colintobing


People also ask

How do you subtract an array in Python?

subtract() function is used when we want to compute the difference of two array.It returns the difference of arr1 and arr2, element-wise. Parameters : arr1 : [array_like or scalar]1st Input array.

How do I subtract two NumPy arrays?

The most straightforward way to subtract two matrices in NumPy is by using the - operator, which is the simplification of the np. subtract() method - NumPy specific method designed for subtracting arrays and other array-like objects such as matrices.

How do you subtract two arrays?

Subtract Two ArraysCreate two arrays, A and B , and subtract the second, B , from the first, A . The elements of B are subtracted from the corresponding elements of A . Use the syntax -C to negate the elements of C .

How do you subtract two matrices in Python?

subtract() to subtract elements of two matrices. It returns the difference of arr1 and arr2, element-wise.


2 Answers

If you have a list of lists for sure, use a nested list comprehension:

In [13]: result = [[e-1 for e in i] for i in n]

In [14]: print result
[[0], [1], [2], [3], [4], [5], [6, 9], [7], [8], [6, 9]]
like image 60
zhangxaochen Avatar answered Nov 01 '22 05:11

zhangxaochen


for x in n:
    for i, y in enumerate(x):
        x[i] = y - 1

This is more efficient, spacewise at least.

or if you want to use nested list comprehension like zhangxaochen did but assign it to the same value so it does it in place:

n[:] = [[b - 1 for b in a] for a in n]

Note that this actually still creates two extra lists so it has the same space complexity as assigning it to a new array.

like image 2
Mdev Avatar answered Nov 01 '22 04:11

Mdev