[英]Modify some elements in 2D python list
My list looks like this: 我的清单如下所示:
board = [ [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
[ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
[ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
[ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
[ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
[ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
[ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
[ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0] ]
How can I modify some of the elements? 如何修改某些元素? Eg: the first element in each row = 0. I want to replace them with fives. 例如:每行的第一个元素=0。我想用5代替它们。 So my list would look like this: 所以我的清单看起来像这样:
board = [ [ 5 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
[ 5 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
[ 5 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
[ 5 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
[ 5 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
[ 5 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
[ 5 , 0 , 0 , 0 , 0 , 0 , 0 , 0],
[ 5 , 0 , 0 , 0 , 0 , 0 , 0 , 0] ]
You can access a specific cell of a 2D array by doing board[r][c]
, where r is the row and c is the column. 您可以通过执行board[r][c]
来访问2D数组的特定单元格,其中r是行,c是列。 For replacing the first column with 5's, you could do: 要用5代替第一列,您可以执行以下操作:
for row in board:
row[0] = 5
This iterates over every row in board
, and sets the first item in each row to 0. 这将遍历board
每一行,并将每一行的第一项设置为0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.