470,811 Members | 1,144 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,811 developers. It's quick & easy.

what list comprehension can't

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

Jul 19 '05 #1
4 1059
I wasn't aware that python supported "if then else".

Jul 19 '05 #2
Hello,

On 24 Jun 2005 11:45:14 -0700, aj****@gmail.com 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
be easier to read.
Christophe
Jul 19 '05 #3
Thank you

pujo

Jul 19 '05 #4
On Fri, 24 Jun 2005 21:04:15 +0200, Christophe Delord wrote:
Hello,

On 24 Jun 2005 11:45:14 -0700, aj****@gmail.com 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
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.
--
Steven.

Jul 19 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

23 posts views Thread by Fuzzyman | last post: by
24 posts views Thread by Mahesh Padmanabhan | last post: by
15 posts views Thread by Darren Dale | last post: by
18 posts views Thread by a | last post: by
4 posts views Thread by Gregory Guthrie | last post: by
4 posts views Thread by bullockbefriending bard | last post: by
11 posts views Thread by beginner | last post: by
1 post views Thread by Ken Pu | last post: by
reply views Thread by mihailmihai484 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.