Multiple 'or' condition in Python [duplicate]

我只是一个虾纸丫 提交于 2019-12-18 12:18:45

问题


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

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.


回答1:


Use not in and a sequence:

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:

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

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

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

if fields[9] not in 'ADENR':



回答2:


You want the in operator:

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

Or, you could use 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:

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.



来源:https://stackoverflow.com/questions/22304500/multiple-or-condition-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!