我的代码使用三个随机数和一些 if 语句来随机移动一个像素。使用 cProfiler,事实证明该函数效率很低。
s = self.surrounding()
surroundingBool = [False if i == None else True for i in s]
r1 = random.random()
r2 = random.random()
r3 = random.random()
if r1 <= 0.333:
if r3 < 0.5 and not surroundingBool[4]: self.x += 1
elif not surroundingBool[3]: self.x -= 1
elif r1 <= 0.666:
if r3 < 0.5 and not surroundingBool[6]: self.y += 1
elif not surroundingBool[1]: self.y -= 1
else:
if r2 < 0.25 and not surroundingBool[7]:
self.x += 1
self.y += 1
elif r2 < 0.5 and not surroundingBool[2]:
self.x += 1
self.y -= 1
elif r2 < 0.75 and not surroundingBool[5]:
self.x -= 1
self.y += 1
elif not surroundingBool[0]:
self.x -= 1
self.y -= 1
self.x %= width
self.y %= height
self.pos = self.y * width + self.x
希望这是不言自明的,但我可以根据需要提供上下文。 我怎样才能使这些 if else 语句更快或更有效?
可以找到完整的代码here如果需要的话。
请您参考如下方法:
这是一种不同的方法,如果您认为它与您的像素移动方法不同,您可以忽略它。由于二维像素阵列中相邻像素最多有八种可能的移动,因此您可以定义一个常量 list 移动并将它们与一个索引配对,该索引指的是从所述产生的像素移动。
根据我对您的代码的解释,这是您可以在 pixel 类的 __init__ 方法中定义的东西。
设置:
changes_1d = (-1, 0, 1)
changes_2d = [(i,j) for j in changes_1d for i in changes_1d if i or j]
self.movements = tuple(enumerate(changes_2d)) # Assign pixel index to each movement
self.movements 的内容:
0 (-1, -1)
1 (0, -1)
2 (1, -1)
3 (-1, 0)
4 (1, 0)
5 (-1, 1)
6 (0, 1)
7 (1, 1)
为什么要这样设置?现在我们可以利用 random.choice() 来快速选择一个随机的二维像素移动,我们可以通过使用 (dx, dy) 返回的索引来检查这个移动是否有效运动对:
def move(self):
s = self.surrounding()
surroundingBool = [i is not None for i in s]
pixel, movement = random.choice(self.movements)
if surroundingBool[pixel]:
self.x += movement[0]
self.y += movement[1]
注意:这是假设移动到周围八个像素中的任何一个像素的概率相同。
但是,我相信 self.surrounding() 函数也可能存在大量低效问题,尤其是在这一行中:
PAI = allPixels[(self.x + x) % width][(self.y + y) % height] if allPixels[(self.x + x) % width][(self.y + y) % height] != None else None
您正在检查像素是否不是 None,然后将其分配给 PAI。尽管如果它是 None,您将 None 分配给 PAI,使 if else 检查变得多余。下面的语句是等价的:
PAI = allPixels[(self.x + x) % width][(self.y + y) % height]
我会提供更多建议,但其中有大量代码可供理解。继续寻找改进方法!
