在python中声明和填充二维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19044174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Declaring and populating 2D array in python
提问by Dangila
I want to declare and populate a 2d array in python as follow:
我想在 python 中声明并填充一个二维数组,如下所示:
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?
但我总是得到 IndexError: list index out of range 异常。有任何想法吗?
采纳答案by Itay Karo
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.
将“行”添加到状态数组的唯一时间是在外部 for 循环之前。
所以 -status[0]
存在但status[1]
不存在。
您需要移动status.append([])
到外部 for 循环内,然后它会在您尝试填充它之前创建一个新的“行”。
回答by justhalf
You haven't increase the number of rows in status
for every value of x
您没有status
为每个值增加行数x
for x in range(0,4):
status.append([])
for y in range(0,4):
status[x].append(randomNo())
回答by Shayne
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]
回答by Pierre H.
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]])
回答by Shayne
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.
它只是一对嵌套的列表推导式。