简体   繁体   中英

Declaring and populating 2D array in python

I want to declare and populate a 2d array in python as follow:

def randomNo():
    rn = randint(0, 4)
    return rn

def populateStatus():
    status = []
    status.append([])
    for x in range (0,4):
        for y in range (0,4):
            status[x].append(randomNo())

But I always get IndexError: list index out of range exception. Any ideas?

You haven't increase the number of rows in status for every value of x

for x in range(0,4):
    status.append([])
    for y in range(0,4):
        status[x].append(randomNo())

Try this:

def randomNo():
  rn = randint(0, 4)
  return rn

def populateStatus():
  status = {}
  for x in range (0,4):
    status [x]={}
    for y in range (0,4):
        status[x][y] = randomNo()

This will give you a 2D dictionary you can access like val=status[0,3]

The only time when you add 'rows' to the status array is before the outer for loop.
So - status[0] exists but status[1] does not.
you need to move status.append([]) to be inside the outer for loop and then it will create a new 'row' before you try to populate it.

More "modern python" way of doing things.

[[ randint(0,4) for x in range(0,4)] for y in range(0,4)]

Its simply a pair of nested list comprehensions.

If you're question is about generating an array of random integers , the numpy module can be useful:

import numpy as np
np.random.randint(0,4, size=(4,4))

This yields directly

array([[3, 0, 1, 1],
       [0, 1, 1, 2],
       [2, 0, 3, 2],
       [0, 1, 2, 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