python中复合条件,Python中的多个“或”条件

博客讨论了Python中代码简洁性的实现,通过比较在IDLE和Eclipse中不同条件检查的效果。建议使用`not in`操作符来替代长串的`and`和`or`,以提高代码的可读性和效率。文中提到了使用元组、集合和字符串的不同方式,并指出在新版本Python中集合的效率更高。
摘要由CSDN通过智能技术生成

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.

解决方案

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':

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值