what list comprehension can't

Discussion in 'Python' started by ajikoe@gmail.com, Jun 24, 2005.

  1. Guest

    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
     
    , Jun 24, 2005
    #1
    1. Advertising

  2. Devan L Guest

    I wasn't aware that python supported "if then else".
     
    Devan L, Jun 24, 2005
    #2
    1. Advertising

  3. Hello,

    On 24 Jun 2005 11:45:14 -0700, 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
     
    Christophe Delord, Jun 24, 2005
    #3
  4. Guest

    Thank you

    pujo
     
    , Jun 24, 2005
    #4
  5. On Fri, 24 Jun 2005 21:04:15 +0200, Christophe Delord wrote:

    > Hello,
    >
    > On 24 Jun 2005 11:45:14 -0700, 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.
     
    Steven D'Aprano, Jun 25, 2005
    #5
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Eric @ Zomething

    Can a List Comprehension do ____ ?

    Eric @ Zomething, Jul 14, 2004, in forum: Python
    Replies:
    6
    Views:
    282
    Duncan Booth
    Jul 15, 2004
  2. Replies:
    6
    Views:
    291
  3. Shane Geiger
    Replies:
    4
    Views:
    407
    bullockbefriending bard
    Mar 25, 2007
  4. Debajit Adhikary
    Replies:
    17
    Views:
    720
    Debajit Adhikary
    Oct 18, 2007
  5. Vedran Furac(
    Replies:
    4
    Views:
    356
    Marc 'BlackJack' Rintsch
    Dec 19, 2008
Loading...

Share This Page