Python中的多个“或”条件

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

Multiple 'or' condition in Python

pythonconditional-statementsmultiple-conditions

提问by katze

I have a little code issue and it works with IDLE and not with Eclipse, can I write this :

我有一个小代码问题,它适用于 IDLE 而不适用于 Eclipse,我可以这样写:

if  fields[9] != ('A' or 'D' or 'E' or 'N' or 'R'):

instead of this :

而不是这个:

if  fields[9] != 'A' and fields[9] != 'D' and fields[9] != 'E' and fields[9] != 'N' and fields[9] != 'R':

Thank you.

谢谢你。

采纳答案by Martijn Pieters

Use not inand a sequence:

使用not in和顺序:

if fields[9] not in ('A', 'D', 'E', 'N', 'R'):

which tests against a tuple, which Python will conveniently and efficiently store as one constant. You could also use a set literal:

它针对一个元组进行测试,Python 将方便有效地将其存储为一个常量。您还可以使用集合文字:

if fields[9] not in {'A', 'D', 'E', 'N', 'R'}:

but only more recent versions of Python (Python 3.2and newer) will recognise this as an immutable constant. This is the fastest option for newer code.

但只有更新的 Python 版本(Python 3.2和更新版本)才会将其识别为不可变常量。这是较新代码的最快选项。

Because this is one character, you could even use a string:

因为这是一个字符,您甚至可以使用字符串:

if fields[9] not in 'ADENR':

回答by mgilson

You want the inoperator:

你想要in运营商:

if fields[9] not in 'ADENR':
    ...

Or, you could use any:

或者,您可以使用any

if not any(fields[9] == c for c in 'ADENR'):
    ...

Or, alternatively, all, which may have a bit more of the same form as the original:

或者, ,all可能与原始形式具有更多相同的形式:

if all(fields[9] != c for c in 'ADENR'):
    ...


As an aside:

作为旁白:

if x != ('A' or 'B' or 'C'):

is really the same thing as saying:

真的和说的是一样的:

if x != 'A':

because 'A' or 'B' or 'C'evaluates to 'A'(Try it!). The reason is because with or, python will return the first "non-falsey" value (or the last one if they're all falsey). Since non-empty strings are non-falsey, the first one gets returned.

因为'A' or 'B' or 'C'评估为'A'(尝试!)。原因是因为 with or,python 将返回第一个“非假”值(如果它们都是假的,则返回最后一个)。由于非空字符串是非假的,第一个被返回。