Search code examples
pythonarrayslistregion

Shorter way to manipulate region of two-dimensional list


In an image processing app I am writing, I have a multidimensional list, data, and I need to be able to access a range of points (say a 2x2 block) at once.

At the moment I am using this:

data[x, y] = average

data[x+1, y] = average

data[x, y+1] = average

data[x+1, y+1] = average

But it's clunky, and if I wanted to expand to a 4x4 or 8x8 block it take 16 or 64 lines of code respectively.

There must be an easier, pythonic way to manipulate regions of a two dimensional list, any ideas?


Solution

  • For an actual 2D list, iterate through the indices you want to use:

    for x in xrange(low_x, low_x+2):
        for y in xrange(low_y, low_y+2):
            data[x][y] = average
    

    For a NumPy array, use a slice assignment:

    data[x:x+2, y:y+2] = average