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]]
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.
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.
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 .
subtract() to subtract elements of two matrices. It returns the difference of arr1 and arr2, element-wise.
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]]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With