在Python中,有什么其他方法可以编写if x == 1或x == 5或x == 10 ......? [英] In Python what's some other ways to write a if x==1 or x==5 or x==10...?

查看:1159
本文介绍了在Python中,有什么其他方法可以编写if x == 1或x == 5或x == 10 ......?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果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

在英语中,重复<$ c似乎是多余的$ c> x ,是否有更容易或更短的方法来写出这样的if语句?

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

也许检查是否存在 x 元组中的值(1,5,10,22,)还是什么?

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.

所以要么

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

myset 东西越有用,你要检查的值越多。 4个值非常少,因此您可以保持简单。 400个值,你应该使用集...

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...

正如Marcin所指出的另一个方面是在集合中查找的必要散列可能比线性搜索列表或元组中的所需值。

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.

这篇关于在Python中,有什么其他方法可以编写if x == 1或x == 5或x == 10 ......?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆