Multiple #39;or#39; 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':
谢谢.
推荐答案
使用 not 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中的多个“或"条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python中的多个“或"条件
基础教程推荐
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
