Python if-else 简写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14461905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:34:09  来源:igfitidea点击:

Python if-else short-hand

pythonpython-2.7

提问by learner

Possible Duplicate:
Ternary conditional operator in Python

可能的重复:
Python 中的三元条件运算符

I want to do the following in python:

我想在 python 中执行以下操作:

while( i < someW && j < someX){
   int x = A[i] > B[j]? A[i++]:B[j++];
   ....
}

Clearly, when either ior jhits a limit, the code will break out of the loop. I need the values of iand joutside of the loop.

显然,当ij达到限制时,代码将跳出循环。我需要的值ij循环外。

Must I really do

我真的必须这样做吗

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?

或者有人知道更短的方法吗?

Besides the above, can I get Python to support something similar to

除了上述之外,我可以让 Python 支持类似于

a,b=5,7
x = a > b ? 10 : 11

回答by DonCallisto

Try this:

尝试这个:

x = a > b and 10 or 11

This is a sample of execution:

这是一个执行示例:

>>> a,b=5,7
>>> x = a > b and 10 or 11
>>> print x
11

回答by Lev Levitsky

The most readable way is

最易读的方式是

x = 10 if a > b else 11

but you can use andand or, too:

但你也可以使用andand or

x = a > b and 10 or 11

The "Zen of Python" says that "readability counts", though, so go for the first way.

不过,“Python 之禅”说“可读性很重要”,所以请选择第一种方式。

Also, the and-or trick will fail if you put a variable instead of 10and it evaluates to False.

此外,如果您放置一个变量而不是10并且它的计算结果为,则 and-or 技巧将失败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

unless you put iand jin a container. But if you show us why you need it, it may well turn out that you don't.

除非你把ij放在一个容器里。但是如果你告诉我们你为什么需要它,结果很可能你不需要。