25

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

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

而不是这个:

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

谢谢你。

4

2 回答 2

39

使用not in和序列:

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

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

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

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

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

if fields[9] not in 'ADENR':
于 2014-03-10T15:37:42.253 回答
14

您希望in运营商:

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

或者,您可以使用any

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

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

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

作为旁白:

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

真的和说的一样:

if x != 'A':

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

于 2014-03-10T15:36:26.020 回答