如何在 Python 中初始化二维数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24023115/
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
How to initialise a 2D array in Python?
提问by Oceanescence
I've been given the pseudo-code:
我得到了伪代码:
for i= 1 to 3
for j = 1 to 3
board [i] [j] = 0
next j
next i
How would I create this in python?
我将如何在 python 中创建它?
(The idea is to create a 3 by 3 array with all of the elements set to 0 using a for loop).
(这个想法是创建一个 3 x 3 的数组,使用 for 循环将所有元素设置为 0)。
采纳答案by arshajii
If you really want to use for
-loops:
如果你真的想使用for
-loops:
>>> board = []
>>> for i in range(3):
... board.append([])
... for j in range(3):
... board[i].append(0)
...
>>> board
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
But Python makes this easier for you:
但是 Python 使您更容易做到这一点:
>>> board = [[0]*3 for _ in range(3)]
>>> board
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
回答by Padraic Cunningham
arr=[[0,0,0] for i in range(3)] # create a list with 3 sublists containing [0,0,0]
arr
Out[1]: [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
If you want an list with 5 sublists containing 4 0's:
如果您想要一个包含 5 个包含 4 个 0 的子列表的列表:
In [29]: arr=[[0,0,0,0] for i in range(5)]
In [30]: arr
Out[30]:
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
The range specifies how many sublists you want, ranges start at 0, so ranges 4 is 0,1,2,3,4
.
gives you five [0,0,0,0]
范围指定您想要的子列表数量,范围从 0 开始,因此范围 4 是0,1,2,3,4
. 给你五个[0,0,0,0]
Using the list comprehension is the same as:
使用列表理解与以下内容相同:
arr=[]
for i in range(5):
arr.append([0,0,0,0])
arr
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
回答by Ben
numpy has something for this:
numpy 有一些东西:
numpy.zeros((3,3))
回答by Chris Mukherjee
If you want something closer to your pseudocode:
如果你想要更接近你的伪代码的东西:
board = []
for i in range(3):
board.append([])
for j in range(3):
board[i].append(0)
回答by dwaodkwadok
You can use the style of pseudocode given or simply just use a python one liner
您可以使用给定的伪代码样式,也可以简单地使用 python one liner
chess_board = [[x]*3 for _ in range(y)] --> list comprehension
chess_board = [[x]*3 for _ in range(y)] --> 列表理解
or you can use the plain loop style of other languages like java. I prefer the one liner as it looks much nicer and cleaner.
或者您可以使用其他语言(如 java)的纯循环样式。我更喜欢单衬,因为它看起来更好更干净。