Velocity Reviews > what list comprehension can't

# what list comprehension can't

ajikoe@gmail.com
Guest
Posts: n/a

 06-24-2005
Hello,

Can we impose if then else into list comprehension ?
Like we do in lambda-map form:

This code change None into 0
L = [None, 12]
R = map(lambda x: (x==None and [0] or x)[0], L) # [0,12]

pujo

Devan L
Guest
Posts: n/a

 06-24-2005
I wasn't aware that python supported "if then else".

Christophe Delord
Guest
Posts: n/a

 06-24-2005
Hello,

On 24 Jun 2005 11:45:14 -0700, http://www.velocityreviews.com/forums/(E-Mail Removed) wrote:

> Hello,
>
> Can we impose if then else into list comprehension ?
> Like we do in lambda-map form:
>
> This code change None into 0
> L = [None, 12]
> R = map(lambda x: (x==None and [0] or x)[0], L) # [0,12]
>

Do you mean:
[(x==None and [0] or [x])[0] for x in L]
or [{None:0}.get(x,x) for x in L]
or [x or 0 for x in L]

Well, the third solution doesn't exactly fit the specification but may

Christophe

ajikoe@gmail.com
Guest
Posts: n/a

 06-24-2005
Thank you

pujo

Steven D'Aprano
Guest
Posts: n/a

 06-25-2005
On Fri, 24 Jun 2005 21:04:15 +0200, Christophe Delord wrote:

> Hello,
>
> On 24 Jun 2005 11:45:14 -0700, (E-Mail Removed) wrote:
>
>> Hello,
>>
>> Can we impose if then else into list comprehension ?
>> Like we do in lambda-map form:
>>
>> This code change None into 0
>> L = [None, 12]
>> R = map(lambda x: (x==None and [0] or x)[0], L) # [0,12]
>>

>
> Do you mean:
> [(x==None and [0] or [x])[0] for x in L]
> or [{None:0}.get(x,x) for x in L]
> or [x or 0 for x in L]
>
> Well, the third solution doesn't exactly fit the specification but may

Or, more generally,

[0 for x in L if x is None]

which doesn't solve the asked-for question, but is a useful feature.

--
Steven.