Home > OS >  Generating 2D matrix in python with all the elements is 0
Generating 2D matrix in python with all the elements is 0

Time:10-17

I'm making a game in python. The map of the game is a stored as matrix with number of line and column are equal, the matrix look kind of like this:

map = [[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]]

I want to make a matrix generator to store it in ram when the game is openned in stead of store the whole matrix like that in the game since the number of line and column are huge(5000 at minimum), there are multiple map size with multiple layer or "floor" for each level and the map's structure will be generate using a random seed.

This is I my last attemp:

def matrix(head):
   return [[0 for c in range(head)] for c in range(head)]

As you see, the c variable is not in used and I don't know if this is the best way to do it.
So I want to know if there's a better way to generate a matrix. Since the matrix is quite big so if can, I want the code to run with little time as possible. Also, I want to avoid using module since the game with be export to .exe file and I want the game as small as possile.

CodePudding user response:

Don't use a python list, use a Numpy array as the memory will be more compact:

def matrix(nrows, ncols):    
    return np.zeros((nrows, ncols), dtype=int)

If you don't want to use numpy, you can use

def matrix(nrows, ncols):
    return [[0] * nrows for _ in range(ncols)]

Note that under the hood, Numpy arrays are pretty much contiguous block of memory for elements with the same size (int in the above example) whereas this is not necessarily the case for a typical Python list as the list can store objects of different types (it actually contains a "pointer" to each element in the list). This makes the latter less compact and slower in general as there will be overhead due to cache misses.

CodePudding user response:

You can do this with numpy

import numpy as np
c = 5000 # your map size
map = np.zeros((c,c))
  • Related