Search code examples
pythonnumpypython-itertools

Can python itertools.imap(func,p,q) work with a conditional test on the index (e.g. to get elements with odd indexes only)?


I have the following arrays

>>> a
array([0, 8, 0, 8, 0, 8])
>>> b
array([0, 6, 0, 6, 0, 6])

these represent the real and imaginary parts of a set of complex numbers.

I can reformat them into numpy.complex datatype using the following

>>> [x for x in itertools.imap(complex,a,b)]
[0j, (8+6j), 0j, (8+6j), 0j, (8+6j)]

However what I really want to get is only the elements with odd indexes:

[(8+6j),(8+6j),(8+6j)]

Is there an easy way to achieve this?


Solution

  • [1::2] takes every other item, starting on index 1 (the second), to the end of the list. That is:

    >>> [x for x in itertools.imap(complex,a,b)][1::2]
    
    [(8+6j), (8+6j), (8+6j)]