如何以更简单的方式写这个

时间:2010-11-11 18:45:18

标签: python optimization refactoring

i = 0
for x in range(0, 5):
    for y in range(0, 5):
        if 0 == outputAfterLearning[i]:
            image.putpixel((x, y), (0, 0, 0))
        elif 1 == outputAfterLearning[i]:
            image.putpixel((x, y), (255, 255, 255))
        i += 1

for x in range(0, 5):
    for y in range(5, 10):
        if 0 == outputAfterLearning[i]:
            image.putpixel((x, y), (0, 0, 0))
        elif 1 == outputAfterLearning[i]:
            image.putpixel((x, y), (255, 255, 255))
        i += 1

for x in range(5, 10):
    for y in range(0, 5):
        if 0 == outputAfterLearning[i]:
            image.putpixel((x, y), (0, 0, 0))
        elif 1 == outputAfterLearning[i]:
            image.putpixel((x, y), (255, 255, 255))
        i += 1

for x in range(5, 10):
    for y in range(5, 10):
        if 0 == outputAfterLearning[i]:
            image.putpixel((x, y), (0, 0, 0))
        elif 1 == outputAfterLearning[i]:
            image.putpixel((x, y), (255, 255, 255))
        i += 1

正如您所看到的,我正在使用5x5px正方形并在其中设置像素来​​迭代图像。

上面的代码非常适合尺寸为10x10px的图像,但我想以更一般的方式编写上面的代码,这样我就可以将它用于更大的图像(例如30x30px)而不添加32个新的for循环。

1 个答案:

答案 0 :(得分:4)

xdim, ydim = 10, 10
xblocksize, yblocksize = 5, 5
for xblock in range(0, xdim, xblocksize):
   for yblock in range(0, ydim, yblocksize):
      for x in range(xblock, xblock+xblocksize):
         for y in range(yblock, yblock+yblocksize):
            # the common code.

但我会为块迭代创建一个生成器:

def blocked(xdim, ydim, xblocksize, yblocksize):
  for xblock in range(0, xdim, xblocksize):
     for yblock in range(0, ydim, yblocksize):
        for x in range(xblock, xblock+xblocksize):
           for y in range(yblock, yblock+yblocksize):
              yield (x, y)

并使用putpixel作为

color = [(0,0,0),(255,255,255)]
for colorcode, pixelloc in zip(outputAfterLearning, blocked(10, 10, 5, 5)):
   if 0 <= colorcode < len(color):
   # ^ omit this if outputAfterLearning[i] is always valid
     image.putpixel(pixelloc, color[colorcode])