Python if 语句的单行多个逻辑比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16424484/
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 22:35:17  来源:igfitidea点击:

Multiple logical comparisons on a single line for an if statement

python

提问by mark mcmurray

I want to do multiple comparisons for a logical condition in python but I am not sure of the right way round for the andand or. I have 2 statements.

我想对 python 中的逻辑条件进行多重比较,但我不确定andand的正确方法or。我有 2 个声明。

Statement 1:

声明 1:

#if PAB is more than BAC and either PAB is less than PAC or PAC is more than BAC
if PAB > BAC and PAB< PAC or PAB > BAC and PAC>BAC: 

Statement 2:

声明 2:

#if PAB is more than BAC and PAC is less than PAB or if PAB is less than BAC and PAC is less than BAC
if PAB >BAC and  PAC<PAB or PAB<BAC and  PAC<BAC

Is or-ing the two ands the correct way to go about it?

or-ing这两个ands是正确的方法吗?

Thanks.

谢谢。

采纳答案by David Heffernan

Looking at statement 1, I'm assuming you mean:

查看语句 1,我假设您的意思是:

if (PAB > BAC and PAB< PAC) or (PAB > BAC and PAC>BAC): 

In which case, I'd probably write it like this (using chained comparisons, docs: python2, python3):

在这种情况下,我可能会这样写(使用链式比较,文档:python2python3):

if (BAC < PAB < PAC) or min(PAB,PAC)>BAC:

You can use an analogous form for statement 2.

您可以对语句 2 使用类似的形式。

Having said that, I cannot make your comments in the question's code match up with my interpretation of your conditionals, so it's plausible I don't understand your requirement.

话虽如此,我无法使您在问题代码中的评论与我对您的条件的解释相匹配,因此我可能不理解您的要求。