what list comprehension can't

A

ajikoe

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
 
C

Christophe Delord

Hello,

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
be easier to read.


Christophe
 
S

Steven D'Aprano

Hello,

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
be easier to read.

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,754
Messages
2,569,528
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top