Pythonic way to create 2d array?

I want to create a 2d array from integer values ​​initially set to 0.

Here's how I could do it:

grid = [[0] * width] * height

But it just creates each line as a link to the original, so something like

grid[0][1] = 1

will change all grid values ​​[n] [1].

This is my decision:

grid = [[0 for x in range(width)] for y in range(height)]

It feels wrong, is there an even more pythonic way to do this?

EDIT: Bonus question, if the grid size never changes and contains only integers, should something like a tuple or array.array be used instead?

+4
source share
3 answers

, * . , 2D- :

[[0] * width for y in range(height)]
+4

numpy.zeros:

import numpy as np
numpy.zeros(height, width)

, dtype=numpy.int8

+1

Here is what I used.

def generate_board(n): #Randomly creates a list with n lists in it, and n random numbers
                       #in each mini list
    list = []
    for i in range(0, n):
        list.append([])
        for j in range(0, n):
            list[i].append(random.randint(0, 9))
    return list

def print_board(board):
    n = len(board) - 1
    while n > -1:
        print str(board[n]) + ' = ' + str(n)
        n -= 1
0
source

Source: https://habr.com/ru/post/1530047/


All Articles