What's the best way to replace the ternary operator in Python?

Possible Duplicate:
Ternary conditional operator in Python

If I have some code like:

x = foo ? 1 : 2

How should I translate it to Python? Can I do this?

if foo:
  x = 1
else:
  x = 2

Will x still be in scope outside the if / then blocks? Or do I have to do something like this?

x = None
if foo:
  x = 1
else:
  x = 2

在Python 2.5+中使用三元运算符(正式条件表达式)。

x = 1 if foo else 2

The Ternary operator mentioned is only available from Python 2.5. From the WeekeePeedeea:

Though it had been delayed for several years by disagreements over syntax, a ternary operator for Python was approved as Python Enhancement Proposal 308 and was added to the 2.5 release in September 2006.

Python's ternary operator differs from the common ?: operator in the order of its operands; the general form is op1 if condition else op2 . This form invites considering op1 as the normal value and op2 as an exceptional case.

Before 2.5, one could use the ugly syntax (lambda x:op2,lambda x:op1)[condition]() which also takes care of only evaluating expressions which are actually needed in order to prevent side effects.


I'm still using 2.4 in one of my projects and have come across this a few times. The most elegant solution I've see for this is:

x = {True: 1, False: 2}[foo is not None]

I like this because it represents a more clear boolean test than using a list with the index values 0 and 1 to get your return value.

链接地址: http://www.djcxy.com/p/7396.html

上一篇: 蟒蛇(布尔)? 那么:else语法?

下一篇: 在Python中替换三元运算符的最好方法是什么?