Shorter, more pythonic way of writing an if statement

后端 未结 6 1695
情书的邮戳
情书的邮戳 2021-01-30 08:38

I have this

bc = \'off\'

if c.page == \'blog\':
    bc = \'on\'

print(bc)

Is there a more pythonic (and/or shorter) way of writing this in Pyth

6条回答
  •  后悔当初
    2021-01-30 09:29

    This is:

    1. definitely shorter
    2. arguably Pythonic (pre-Python 2.5, which introduced the controversial X if Z else Y syntax)
    3. questionably readable. With those caveats in mind, here it goes:

      bc = ("off","on")[c.page=="blog"]
      

    EDIT: As per request, the generalized form is:

       result = (on_false, on_true)[condition]
    

    Explanation: condition can be anything that evaluates to a Boolean. It is then treated as an integer since it is used to index the tuple: False == 0, True == 1, which then selects the right item from the tuple.

提交回复
热议问题