Search code examples
pythonarrayscpython

python fastest way to divide multi dimensional list


dealing with optimize dividing 2 dimensional list a = [[0, 2169, 5454], [1878, 0, 454]] by an integer value, to get an integer result: right now I have a wildly inefficient for loop - I have read some of the documentation about mapping to int, and using list comprehension, but struggling to understand how to make it work for a two dimensional list

   for row in range(0, len(a)):
      for col in range(0, len(a[row])):
          a[row][col] = int(a[row][col] / 600)

Solution

  • you don't need the range loops, you can use a list comp:

    a[:] = [[ele // 600 for ele in sub] for sub in a]
    

    a[:] will change the original list the same as your code is doing just with the efficiency of a list comp. If you want any real further significant improvement you should look at numpy.

    import numpy as np
    
    a = np.array(a)
    
    a //=  600
    
    print(a)
    [[0 3 9]
     [3 0 0]]