在 python 中将随机整数添加到网格的外部单元格



我有一个游戏的网格,如下所示:

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"。

有没有办法在保持更改网格大小并仍然执行相同操作的能力的同时快速执行此操作?

提前感谢!

首先你应该使用列表而不是元组,元组是不可变的,不能更改。

将网格创建为包含列表的列表

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]]

这应该可以解决问题,尽管其中一位蟒蛇大师可能有一个更简单的解决方案。

初版

#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 以使代码更具可读性

再版

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)

如果有人指出一种更简单/更具可读性的方式来做到这一点,我会很高兴。

如果您将网格表示为列表列表(而不是元组列表),那么只需迭代外部单元格并设置:

grid[x][y] = random.randint(0, 1)

。考虑到"随机转动它们"的意思是"以 50% 的概率改变它们"。

你可以使用 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))

扩展 Jan 的答案

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。

您应该通过 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()

最新更新