extract multiple ranges from a list

Peter Otten __peter__ at web.de
Sat Mar 8 17:32:15 CET 2008


pi.arctan at gmail.com wrote:

> One of my many project involves working with YUV-files, where I need
> to reduce
> the vertical resolution with a factor of two, i.e. remove every other
> scan line.
> Today I'm using two for-loops in the fashion shown below
> 
> y = []
> for i in range(0, width*height, width*2):
>     for j in range(0,width):
>         y.append(Y[i+j])
> 
> This approach doesn't feel very pythonic but I can't come up with a
> better idea to do it.
> I've tried list comprehension and map together with lambda but I can't
> get a flattened list
> of every other scan-line...
> 
> CIF = 352x288 items for luminance and the aim is to have the list
> below:
> y = [0:352 704:1056 ... ]

>>> width = 3; height = 5
>>> Y = range(width*height)
>>> y = []
>>> for i in range(0, width*height, 2*width):
...     y.extend(Y[i:i+width])
...
>>> y
[0, 1, 2, 6, 7, 8, 12, 13, 14]

Probably more efficient, but needs numpy:

>>> import numpy
>>> width = 3
>>> height = 5
>>> Y = range(width*height)
>>> a = numpy.array(Y).reshape(height, width)
>>> a
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [12, 13, 14]])
>>> b = a[::2]
>>> b
array([[ 0,  1,  2],
       [ 6,  7,  8],
       [12, 13, 14]])
>>> list(b.reshape(len(b)*width))
[0, 1, 2, 6, 7, 8, 12, 13, 14]

Peter




More information about the Python-list mailing list