Python中的多个“或”条件 [英] Multiple 'or' condition in Python
本文介绍了Python中的多个“或”条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个小代码问题,它适用于IDLE,而不适用于Eclipse,我可以这样写吗:
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'):
代替此:
if fields[9] != 'A' and fields[9] != 'D' and fields[9] != 'E' and fields[9] != 'N' and fields[9] != 'R':
谢谢。
推荐答案
不使用 in
和一个序列:
if fields[9] not in ('A', 'D', 'E', 'N', 'R'):
,用于对元组进行测试, Python将方便,有效地将其存储为一个常量。您还可以使用设置的文字:
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'}:
,但仅Python( Python 3.2 及更高版本)会将其识别为不变的常量。这是更新代码最快的选择。
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':
这篇关于Python中的多个“或”条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文