Home > database >  How to create a 2D array where all elements have the same number?
How to create a 2D array where all elements have the same number?

Time:02-21

I would like to create an array size 576x720 where each element has the same number.

I tried it like this but did not succeed:

#Define row and column
int row = 576, col = 720;
#Initialize 2D character array
char array2D[row][col] = {[0 ... (row-1)][0 ... (col-1)] = '137'};

How can I create such an array?

CodePudding user response:

Personally speaking, the easiest way would be using numpy module and full function:

row = 576
col = 720
valueToFill = 137
numpy.full((row, col), valueToFill)

Output

array([[137, 137, 137, ..., 137, 137, 137],
       [137, 137, 137, ..., 137, 137, 137],
       [137, 137, 137, ..., 137, 137, 137],
       ...,
       [137, 137, 137, ..., 137, 137, 137],
       [137, 137, 137, ..., 137, 137, 137],
       [137, 137, 137, ..., 137, 137, 137]])

If you wanna make sure the shape of the matrix is as same as what you asked for, you can try calling shape attribute on the array:

row = 576
col = 720
valueToFill = 1
array = numpy.full((row, col), valueToFill)
array.shape

which results in:

(576, 720)

CodePudding user response:

Here it is:

row,col = 576, 720
array2D = [[137]*row for i in range(col)]
  • Related