代码之家  ›  专栏  ›  技术社区  ›  Richard Knop

如何用更简单的方式来写

  •  3
  • Richard Knop  · 技术社区  · 14 年前
    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
    

    上面的代码对于尺寸为10x10px的图像是显而易见的,但是我想用一种更通用的方式编写上面的代码,这样我就可以在不增加32个for循环的情况下使用它来处理更大的图像(比如30x30px)。

    1 回复  |  直到 14 年前
        1
  •  4
  •   kennytm    14 年前
    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)
    

    使用putpoixel作为

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