python中x[1=5是什么意思_在Python中,有什么其他方法可以编写if x == 1或x == 5或x == 10 ......?...

I often end up writing code like

if x == 1 or x == 5 or x == 10 or x == 22 :

pass

In English it seems redundant to keep repeating x, is there an easier or shorter way to write out an if-statement like that?

Maybe checking of existence of x's value in a tuple ( 1, 5, 10, 22, ) or something?

解决方案

Yes, you are right - either in a tuple or (if this check is made repeatedly) in a set.

So either do

if x in (1, 5, 10, 22):

pass

or, if you do this check often and the number of values is large enough,

myset = set((1, 5, 10, 22))

[...]

if x in myset:

pass

The myset stuff is the more useful, the more values you want to check. 4 values are quite few, so you can keep it simple. 400 values and you should use the set...

Another aspect, as pointed out by Marcin, is the necessary hashing for lookup in the set which may be more expensive than linearly searching a list or tuple for the wanted value.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值