Python中的多个“或”条件

kat*_*tze 18 python multiple-conditions conditional-statements

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

if  fields[9] != ('A' or 'D' or 'E' or 'N' or 'R'):
Run Code Online (Sandbox Code Playgroud)

代替这个:

if  fields[9] != 'A' and fields[9] != 'D' and fields[9] != 'E' and fields[9] != 'N' and fields[9] != 'R':
Run Code Online (Sandbox Code Playgroud)

谢谢。

Mar*_*ers 32

使用not in和顺序:

if fields[9] not in ('A', 'D', 'E', 'N', 'R'):
Run Code Online (Sandbox Code Playgroud)

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

if fields[9] not in {'A', 'D', 'E', 'N', 'R'}:
Run Code Online (Sandbox Code Playgroud)

但只有Python的最新版本(Python 3.2和更高版本)才会将此视为不变的常量。对于更新的代码,这是最快的选择。

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

if fields[9] not in 'ADENR':
Run Code Online (Sandbox Code Playgroud)


mgi*_*son 11

您想要in操作员:

if fields[9] not in 'ADENR':
    ...
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用any

if not any(fields[9] == c for c in 'ADENR'):
    ...
Run Code Online (Sandbox Code Playgroud)

或者,或者,all其形式可能会与原始版本略有不同:

if all(fields[9] != c for c in 'ADENR'):
    ...
Run Code Online (Sandbox Code Playgroud)

作为旁白:

if x != ('A' or 'B' or 'C'):
Run Code Online (Sandbox Code Playgroud)

的确与说同样的话:

if x != 'A':
Run Code Online (Sandbox Code Playgroud)

因为'A' or 'B' or 'C'评估为'A'(尝试!)。原因是因为有了or,python将返回第一个“ non-falsey”值(如果所有均为false,则返回最后一个值)。由于非空字符串是非伪字符串,因此将返回第一个。