在Python中替换三元运算符的最佳方法是什么?

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

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Ternary conditional operator in Python

如果我有这样的代码:

1
x = foo ? 1 : 2

我应该如何将其转换为python?我可以这样做吗?

1
2
3
4
if foo:
  x = 1
else:
  x = 2

X是否仍在if/then块之外的范围内?还是我必须做这样的事?

1
2
3
4
5
x = None
if foo:
  x = 1
else:
  x = 2


在python 2.5+中使用三元运算符(形式上是条件表达式)。

1
x = 1 if foo else 2


上面提到的三元运算符只能从python 2.5中获得。从Peedeea周开始:

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.


我还在我的一个项目中使用2.4,并且已经遇到过几次了。我看到的最优雅的解决方案是:

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

我喜欢这个,因为它代表了一个比使用索引值为0和1的列表来获取返回值更清晰的布尔测试。


这个的副本。

我使用这个(尽管我在等待有人投反对票或评论,如果不正确的话):

1
x = foo and 1 or 2


您可以使用如下内容:

1
2
3
val = float(raw_input("Age:"))
status = ("working","retired")[val>65]
print"You should be",status

虽然不是很像Python

(其他选项更接近C/Perl,但这涉及更多的元组魔力)


一个不错的python技巧是使用:

1
foo = ["ifFalse","ifTrue"][booleanCondition]

它创建一个2成员的列表,布尔值变为0(假)或1(真),从而选择正确的成员。不太可读,但Python:)