Modifying every alternate element of a sequence
Tim Chase
python.list at tim.thechases.com
Tue Nov 28 06:18:18 EST 2006
> I have a list of numbers and I want to build another list with every
> second element multiplied by -1.
>
> input = [1,2,3,4,5,6]
> wanted = [1,-2,3,-4,5,-6]
>
> I can implement it like this:
>
> input = range(3,12)
> wanted = []
> for (i,v) in enumerate(input):
> if i%2 == 0:
> wanted.append(v)
> else:
> wanted.append(-v)
>>> input = range(3,12)
>>> [i%2==0 and v or -v for (i,v) in enumerate(input)]
[3, -4, 5, -6, 7, -8, 9, -10, 11]
> But is there any other better way to do this.
I'm not sure densely packing it into a list comprehension is
necessarily a *better* way, just a more compact way.
To make more sense of it, you might create a helper function that
does your comparison work:
def inv_if(v, test):
if test:
return v
else:
return -v
[inv_if(v, i%2==0) for (i,v) in enumerate(input)]
Or you could even do something like
def inv_alternating(t):
i, v = t
if i%2==0:
return v
else:
return -v
[inv_alternating(t) for t in enumerate(input)]
Either compacts it for the actual call within a list
comprehension, but it is cleaner to read what's going on.
-tkc
More information about the Python-list
mailing list