About a list comprehension to transform an input list
Julio Sergio
juliosergio at gmail.com
Fri Jun 8 12:10:15 EDT 2012
>From a sequence of numbers, I'm trying to get a list that does something to even
numbers but leaves untouched the odd ones, say:
[0,1,2,3,4,...] ==> [100,1,102,3,104,...]
I know that this can be done with an auxiliary function, as follows:
->>> def filter(n):
... if (n%2 == 0):
... return 100+n
... return n
...
->>> L = range(10)
->>> [filter(n) for n in L]
[100, 1, 102, 3, 104, 5, 106, 7, 108, 9]
I wonder whether there can be a single list comprehension expression to get this
result without the aid of the auxiliary function.
Do you have any comments on this?
Thanks,
--Sergio.
More information about the Python-list
mailing list