Shorter, more pythonic way of writing an if statement

后端 未结 6 1705
情书的邮戳
情书的邮戳 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:13

    Another possibility is to use a dict if you can compute the values outside of the function that accesses them (i.e. the values are static, which also addresses the evaluation issue in scrible's answer's comments).

    want_bc = {True: "on", False: "off"}
    # ...
    bc = want_bc[c.page == "blog"]
    

    I prefer this and/or the tuple indexing solutions under the general rubric of preferring computation to testing.

提交回复
热议问题