Home > database >  2D list divided by another 2D list
2D list divided by another 2D list

Time:09-24

I have two 2-D list:

A = [[10,20,30],
     [5,8,10]]

B = [[1,2,5],
     [5,4,2]]

The output should be:

result = [[10,10,6],
          [1,2,5]]

What is the most efficient way to achieve this? I could only think of nested for loop which is pretty complicated...

CodePudding user response:

You mentioned the tag numpy, then use it.

If they're not already numpy arrays, first convert them:

A = np.array(A)
B = np.array(B)

Then divide them:

>>> A / B
array([[10., 10.,  6.],
       [ 1.,  2.,  5.]])
>>> 

As @sj95126 mentioned, to make it integer type values and a list, use:

>>> (A / B).astype(int).tolist()
[[10, 10, 6], [1, 2, 5]]
>>> 

Or as @wjandrea mentioned, you could make them integers already in the beginning:

A = np.array(A, dtype='int')
B = np.array(B, dtype='int')

Then do:

>>> (A // B).tolist()
[[10, 10, 6], [1, 2, 5]]
>>> 

CodePudding user response:

You can use np.floor_divide, which is equivalent to // and converts its inputs to arrays automatically:

>>> np.floor_divide(A, B)
array([[10, 10,  6],
       [ 1,  2,  5]])

A list comprehension would be a non-numpy solution free of libraries:

>>> [[a // b for a, b in zip(*rows)] for rows in zip(A, B)]
[[10, 10, 6], [1, 2, 5]]
  • Related