简体   繁体   中英

Creating a 2d Array in Python

How do you make a 2d grid? Next, how do you replace random elements in that grid with something else?

I tried:

def introgrid( ):
     anyrow = 0
     print(columnrow)
     grid = [symbol for r in range(column)]
     grid2 = (grid[0]+"  ")*15
     for i in range(row):
         print(grid2+str(anyrow))
         anyrow+=1

symbol= "."
columnn= 15
row= 12
rowcount = 0
columnrow = "0  1  2  3  4  5  6  7  8  9  10 11 12 13 14"

This produces a grid but it doesn't let you change elements of it randomly. HELP!

To make a 2D array you could write

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

And to access items in the grid just enter grid[x][x] where x is your position

Edit

I find the other answers to complicated. This actually gives you a grid. It's just a matter of how you present the data.

To print a 2D array as a grid representation you only have to iterate through the array

for item in grid:
   row = ''
   for subitem in item:
       row += str(subitem) + ' '
   print row

And to change every value in the the array, you could do:

for index, item in enumerate(grid):
    for subindex, subitem in enumerate(item):
        grid[index][subindex] = random.randint(0, 10)

Generally, I have seen grids represented as lists in lists. Ie if you want to make the following grid:

A0 B0 C0
A1 B1 C1
A2 B2 C2

you would represent it like so (keeping in mind that arrays/lists in python are zero-indexed :

[[A0, B0, C0],
[A1, B1, C1],
[A2, B2, C2]]

There are of course multiple variations to this sort of thing. One example that springs to mind is that you could store each row as a separate numbered attribute of an object. Since you are using lists (arrays) in your example, I'm going to assume you're going for an list-base representation.

You have variables which I understand as follows: column is the number of columns on the grid's x-axis, and row in the number of rows on the columns y-axis. It's generally good practice to make your variable names as clear as possible, so I'm going to use num_rows and num_cols instead.

If you want to make a grid, first you instantiate your rows, then you add your columns to each row. You could use a list comprehension, but those are probably harder to read that for loops. Using for loops, you would make a grid like so:

SYMBOL = '.' # it is convention in python to name constants in ALL CAPS
grid = []

for x in range(num_rows):
    grid.append([])
    for y in range(num_cols):
        grid[x].append(SYMBOL)

To access a random element, just use python's built-in random number generator .

from random import randint

row = randint(0,num_rows-1)
col = randint(0,num_cols-1)

value = 'whatever you want to put in the random cell'

grid[row][col] = value

You can use for instance the .join() method of the string class to join some random symbols at each row, and then print it instead of dots. The random symbols can be obtained with the function random.choice(list) that randomly returns element taken into list . Here is the application to your case, where my list is the available uppercase chars and digits. You can play with it to select different random symbols.

import string
import random

% Grid dimensions and column numbers 
cols = 15
rows = 12
column = ' '.join(str(i).zfill(2) for i in range(cols))

% Turn the basic symbol into a string
basic_symbol= '.'
grid = '  '.join(basic_symbol for i in range(cols))

% Display the grid
print(column)
for i in range(rows):
    randgrid = '  '.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(cols))
    print randgrid + ' ' + str(i).zfill(2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM