在python中向网格的外部单元格添加随机整数
我有一个游戏网格,如下所示:在python中向网格的外部单元格添加随机整数,python,arrays,grid,Python,Arrays,Grid,我有一个游戏网格,如下所示: grid = [(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)] 我需要遍历网格的外部单元格,并随机将它们转换为“1”或“0” 有没有一种方法可以在保持更改网格大小的能力的同时快速执行此操作,并且仍然执行相同的操作 提前谢谢 您可以使用numpy,而且根本不需要迭代 import n
grid = [(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)]
我需要遍历网格的外部单元格,并随机将它们转换为“1”或“0”
有没有一种方法可以在保持更改网格大小的能力的同时快速执行此操作,并且仍然执行相同的操作
提前谢谢 您可以使用numpy,而且根本不需要迭代
import numpy as np
grid = np.array([(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)])
grid[[0,-1]] = np.random.randint(2,size=(2,grid.shape[1]))
grid[:,[0,-1]] = np.random.randint(2,size=(grid.shape[0],2))
如果将网格表示为列表列表(而不是元组列表),则需要迭代外部单元格并设置:
grid[x][y] = random.randint(0, 1)
。。。考虑到“随机转换它们”的意思是“以50%的概率更改它们”。首先,您应该使用列表而不是元组,元组是不可变的,不能更改 使用列表创建网格作为列表
grid = [[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]]
这应该可以做到,尽管python大师之一可能有一个更简单的解决方案
第一版
#go through all the lines
for index, line in enumerate(grid):
#is the line the first or the last one
if index == 0 or index == len(grid)-1:
#randomize all entries
for i in range(0, len(line)):
line[i] = randint(0, 1)
#the line is one in the middle
else:
#randomize the first and the last
line[0] = randint(0, 1)
line[-1] = randint(0, 1)
for index, line in enumerate(grid):
if index == 0 or index == len(grid)-1:
grid[index] = [randint(0, 1)for x in line]
else:
line[0] = randint(0, 1)
line[-1] = randint(0, 1)
在进一步研究之后,我可以用列表理解替换嵌套的for,以使代码更具可读性
第二版
#go through all the lines
for index, line in enumerate(grid):
#is the line the first or the last one
if index == 0 or index == len(grid)-1:
#randomize all entries
for i in range(0, len(line)):
line[i] = randint(0, 1)
#the line is one in the middle
else:
#randomize the first and the last
line[0] = randint(0, 1)
line[-1] = randint(0, 1)
for index, line in enumerate(grid):
if index == 0 or index == len(grid)-1:
grid[index] = [randint(0, 1)for x in line]
else:
line[0] = randint(0, 1)
line[-1] = randint(0, 1)
如果有人指出一种更容易/更易读的方法,我会很高兴。您应该通过numpy模块使用数组来提高性能,如下所示:
import numpy as np
from random import randint
def random_grid():
while True:
grid = np.array([randint(0, 1) for _ in range(35)]).reshape(5,7)
yield grid
gen_grids = random_grid()
print gen_grids.next()
扩展简的答案
from random import randint
grid = [[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]]
for x, j in enumerate(grid):
for y, i in enumerate(j):
grid[x][y] = randint(0,1)
print(grid)
这是一个简单的解决方案,与大小无关,但如果性能至关重要,则选择numpy。如果这是一个游戏网格,您可能更应该使用列表列表而不是元组列表,因为元组是不可变的。然而,就我个人而言,我可能会定义自己的类来表示董事会。在上面的注释之后,“不可变”意味着元组(用括号表示)不能更改。要更改外部单元格,您需要一些可变的内容(如建议的列表)。