简体   繁体   English

在python中声明和填充2D数组

[英]Declaring and populating 2D array in python

I want to declare and populate a 2d array in python as follow: 我想在python中声明并填充2d数组,如下所示:

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. 但是我总是得到IndexError:列表索引超出范围异常。 Any ideas? 有任何想法吗?

You haven't increase the number of rows in status for every value of x 您没有为x每个值增加status的行数

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] 这将为您提供2D词典,您可以像val=status[0,3]那样访问

The only time when you add 'rows' to the status array is before the outer for loop. 将“行”添加到状态数组的唯一时间是在外部for循环之前。
So - status[0] exists but status[1] does not. 因此status[0]存在,但status[1]不存在。
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. 您需要将status.append([])移动到外部for循环内,然后在尝试填充它之前将创建一个新的“行”。

More "modern python" way of doing things. 更多的“现代python”做事方式。

[[ 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: 如果您对生成随机整数数组有疑问,那么numpy模块可能会有用:

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]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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