Modifying every alternate element of a sequence
bearophileHUGS at lycos.com
bearophileHUGS at lycos.com
Tue Nov 28 15:08:36 EST 2006
Leo Kislov:
> input[1::2] = [-item for item in input[1::2]]
> If you don't want to do it in-place, just make a copy:
> wanted = input[:]
> wanted[1::2] = [-item for item in wanted[1::2]]
Very nice solution.
I have tried few versions like:
from itertools import imap, islice
from operator import neg
1) data[1::2] = [-el for el in data[1::2]]
2) data[1::2] = map(neg, data[1::2])
3) data[1::2] = imap(neg, data[1::2])
4) data[1::2] = map(neg, islice(data, 1, None, 2))
5) etc.
With Python 2.5 it seems that the n.2 (map + slicing) is the faster.
Bye,
bearophile
More information about the Python-list
mailing list