Python - Easy and Fast Way to Divide Values in a 2D List by a Single Value

aegc :

For example I have a 2D list of 2x2 dimension stored in a variable r.

 12    24
 36    48

I want to divide every value in the list by 2. An easy slow way to do this is to iterate through each row and column and divide it by 2.

rows = 2
columns = 2
for x in range(rows):
    for y in range(columns):
        r[x][y] = r[x][y]/2

Is there an easy and fast way to divide each values in a 2D list to a specific value other than the manual approach? I tried the code below but it throws an error:

 s = r /2

Error:

TypeError: unsupported operand type(s) for /: 'list' and 'int'
Shubham Sharma :

You can use numpy library to achieve the result you want. it uses vectorization so its the fastest way to do the operation.

Try this:

import numpy as np

arr = np.array(r) # --> initialize with 2d array
arr = arr / 2 # --> Now each element in the 2d array gets divided by 2

For Example:

arr = np.array([[1, 2], [2, 3]]) # --> initialize with 2d array
arr = arr / 2 # --> divide by the scalar

print(arr)

Output:

[[0.5 1. ]
 [1.  1.5]]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=360869&siteId=1
Recommended