4

我想知道 python 中的等价物是什么:

n = 100
x = (10 < n) ? 10 : n;
print x;

由于某种原因,这在 Python 中不起作用。我知道我可以使用 if 语句,但我只是好奇是否有一些更短的语法。

谢谢。


如何创建设置但全局重定向?

我需要,当一个人来到 mysite.com/index.html -> refirect to mysite.com/index.php 或

mysite.com/index.phtml -> mysite.com/index.php。或 mysite.com/index.sdsf -> mysite.com/index.php。或者

mysite.com/about.phtml -> mysite.com/about.php。

4

6 回答 6

17
x = min(n, 10)

或者,更一般地说:

x = 10 if 10<n else n
于 2011-01-30T13:13:03.443 回答
7

这是 Python 中的三元运算符(在文档中也称为条件表达式)。

x if cond else y
于 2011-01-30T13:12:36.537 回答
4

三元运算有多种方式,第一种是2.5中添加的表达式:

n = foo if condition else bar

如果你想与低于 2.5 的版本兼容,你可以利用布尔值是子类的事实,int它的True行为类似于1,而False行为类似于0

n = [bar, foo][condition]

另一种可能性是利用 Python 中运算符的行为方式或更准确的方式andor行为方式:

n = condition and foo or bar
于 2011-01-30T13:49:20.240 回答
1
>>> n = 100
>>> x = 10 if n > 10 else n
>>> x
10
于 2011-01-30T13:13:10.580 回答
1
10 if 10 < n else n 

http://en.wikipedia.org/wiki/Ternary_operation

于 2011-01-30T13:13:20.387 回答
1
x = 10 if (10 < n) else n

(需要python 2.5)

于 2011-01-30T13:13:22.050 回答