On 6/8/2012 9:17 AM Daniel Urban said...
On Fri, Jun 8, 2012 at 6:10 PM, Julio Sergio<julioser...@gmail.com>  wrote:
> 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?

l = [0,1,2,3,4,5,6,7,8,9]
[n if n%2 else 100+n for n in l]
[100, 1, 102, 3, 104, 5, 106, 7, 108, 9]


Or alternately by leveraging true/false as 1/0:

>>> [ 100*(not(ii%2))+ii for ii in range(10)]
[100, 1, 102, 3, 104, 5, 106, 7, 108, 9]
>>> [ 100*(ii%2)+ii for ii in range(10)]
[0, 101, 2, 103, 4, 105, 6, 107, 8, 109]


--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to