编写if语句的更短,更pythonic的方式 [英] Shorter, more pythonic way of writing an if statement

查看:130
本文介绍了编写if语句的更短,更pythonic的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个

bc = 'off'

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

print bc

在python中有更多pythonic(和/或更短)的写法吗?

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

推荐答案

最短的应该是:

bc = 'on' if c.page=='blog' else 'off'

通常这可能看起来有点令人困惑,所以你应该只在它清楚它意味着什么时才使用它。不要将它用于大布尔条款,因为它开始看起来很难看。

Generally this might look a bit confusing, so you should only use it when it is clear what it means. Don't use it for big boolean clauses, since it begins to look ugly fast.

这篇关于编写if语句的更短,更pythonic的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆