Python if-else 简写 [英] Python if-else short-hand
问题描述
可能的重复:
Python 中的三元条件运算符
我想在 python 中执行以下操作:
I want to do the following in python:
while( i < someW && j < someX){
int x = A[i] > B[j]? A[i++]:B[j++];
....
}
显然,当 i
或 j
达到极限时,代码将跳出循环.我需要循环之外的 i
和 j
的值.
Clearly, when either i
or j
hits a limit, the code will break out of the loop. I need the values of i
and j
outside of the loop.
我真的必须这样做
x=0
...
if A[i] > B[j]:
x = A[i]
i+=1
else:
x = B[j]
j+=1
或者有人知道更短的方法吗?
Or does anyone know of a shorter way?
除此之外,我是否可以让 Python 支持类似的东西
Besides the above, can I get Python to support something similar to
a,b=5,7
x = a > b ? 10 : 11
推荐答案
最易读的方式是
x = 10 if a > b else 11
但是你也可以使用and
和or
:
x = a > b and 10 or 11
不过,Python 之禅"说可读性很重要",所以请选择第一种方式.
The "Zen of Python" says that "readability counts", though, so go for the first way.
此外,如果你放置一个变量而不是 10
并且它的计算结果为 False
,那么 and-or 技巧就会失败.
Also, the and-or trick will fail if you put a variable instead of 10
and it evaluates to False
.
然而,如果比赋值更多地依赖于这个条件,那么按照你的方式编写它会更具可读性:
However, if more than the assignment depends on this condition, it will be more readable to write it as you have:
if A[i] > B[j]:
x = A[i]
i += 1
else:
x = A[j]
j += 1
除非您将 i
和 j
放入容器中.但是如果你告诉我们你为什么需要它,结果很可能你不需要.
unless you put i
and j
in a container. But if you show us why you need it, it may well turn out that you don't.
这篇关于Python if-else 简写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!