Python中的条件运算符? [英] Conditional operator in Python?

查看:34
本文介绍了Python中的条件运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你知道 Python 是否支持一些关键字或表达式,如 C++ 中的基于 if 条件返回值,都在同一行(C++ if 用问号 ?)

do you know if Python supports some keyword or expression like in C++ to return values based on if condition, all in the same line (The C++ if expressed with the question mark ?)

// C++
value = ( a > 10 ? b : c )

推荐答案

从 Python 2.5 开始,您可以:

From Python 2.5 onwards you can do:

value = b if a > 10 else c

以前,您必须执行以下操作,尽管由于短路效应丢失,语义不相同:

Previously you would have to do something like the following, although the semantics isn't identical as the short circuiting effect is lost:

value = [c, b][a > 10]

还有另一种使用and ... or"的技巧,但最好不要使用它,因为它在某些情况下会产生不良行为,导致难以发现错误.我什至不会在这里写 hack 因为我认为最好不要使用它,但是您可以在 维基百科,如果你愿意.

There's also another hack using 'and ... or' but it's best to not use it as it has an undesirable behaviour in some situations that can lead to a hard to find bug. I won't even write the hack here as I think it's best not to use it, but you can read about it on Wikipedia if you want.

这篇关于Python中的条件运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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