[英]Randomly iterating through a 2D list in Python
My first attempt to accomplish this resulted in: 我实现这一目标的第一次尝试导致:
def rand_Random(self):
randomRangeI = range(self.gridWidth)
shuffle(randomRangeI)
randomRangeJ = range(self.gridHeight)
shuffle(randomRangeJ)
for i in randomRangeI:
for j in randomRangeJ:
if self.grid[i][j] != 'b':
print i, j
self.grid[i][j].colour = self.rand_Land_Picker()
Which has the issue of going through one inner list at a time: 哪个问题一次只能通过一个内部列表:
[1][1..X] [1] [1..X]
[2][1..X] [2] [1..X]
What I'd like to be able to do is iterate through the 2d array entirely at random (with no repeats). 我希望能够做的是完全随机迭代2d数组(没有重复)。
Anyone have any solutions to this problem? 任何人都有解决这个问题的方法吗?
Edit: Thanks for the replies, it appears the way I view 2d arrays in my mind is different to most! 编辑:感谢您的回复,看起来我在脑海中观看2D阵列的方式与大多数人不同!
Create an array with all possible pairs of coordinates, shuffle this and iterate through as normal. 创建一个包含所有可能坐标对的数组,将其拖曳并正常迭代。
import random
coords = [(x,y) for x in range(self.gridWidth) for y in range(self.gridHeight)
random.shuffle(coords)
for i,j in coords:
if self.grid[i][j] != 'b':
print i, j
self.grid[i][j].colour = self.rand_Land_Picker()
You can consider 2D array as 1D array and randomly iterate through it. 您可以将2D数组视为一维数组并随机迭代它。
def rand_Random(self):
randomRange = range(self.gridWidth*self.gridHeight)
shuffle(randomRange)
for index in randomRange:
i = index / self.gridWidth
j = index % self.gridWidth
if self.grid[i][j] != 'b':
print i, j
self.grid[i][j].colour = self.rand_Land_Picker()
You can do something like: 你可以这样做:
randomRange = range(w*h)
shuffle(randomRange)
for n in randomRange:
i = n/w
j = n%w
Here randomRange
basically enumerates all the coordinates from 0
to w*h-1
. 这里
randomRange
基本上枚举了从0
到w*h-1
所有坐标。
Even prettier, i
and j
, can be found in one statement: 更漂亮的,
i
和j
,可以在一个声明中找到:
i,j = divmod(n, w)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.