如何在Python中初始化2D数组? [英] How to initialise a 2D array in Python?
本文介绍了如何在Python中初始化2D数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经得到了伪代码:
for i= 1 to 3
for j = 1 to 3
board [i] [j] = 0
next j
next i
如何在python中创建它?
How would I create this in python?
(这个想法是使用for循环创建一个3 x 3的数组,并将所有元素都设置为0).
(The idea is to create a 3 by 3 array with all of the elements set to 0 using a for loop).
推荐答案
如果您真的想使用for
-loops:
If you really want to use 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]]
但是Python使您更轻松:
But Python makes this easier for you:
>>> board = [[0]*3 for _ in range(3)]
>>> board
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
这篇关于如何在Python中初始化2D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文