检查Python中的数字是否不在范围内

时间:2016-04-08 19:37:03

标签: python range

好的,所以我现在有Python代码可以这样做:

if plug in range(1, 5):
    print "The number spider has disappeared down the plughole"

但我真正想做的是检查数字是否不在范围内。我用Google搜索并查看了Python文档但我无法找到任何内容。有什么想法吗?

其他数据:运行此代码时:

if not plug in range(1, 5):
    print "The number spider has disappeared down the plughole"

我收到以下错误:

Traceback (most recent call last):
    File "python", line 33, in <module>
IndexError: list assignment index out of range

我也尝试过:

if plug not in range(1,5):
     print "The number spider has disappeared down the plughole"

返回了相同的错误。

5 个答案:

答案 0 :(得分:13)

如果你的范围是step,那么它的性能提升速度要快得多:

if not 1 <= plug < 5:

使用其他人建议的not方法:

if plug not in range(1, 5)

证明:

>>> import timeit
>>> timeit.timeit('1 <= plug < 5', setup='plug=3')  # plug in range
0.053391717400628654
>>> timeit.timeit('1 <= plug < 5', setup='plug=12')  # plug not in range
0.05137874743129345
>>> timeit.timeit('plug not in r', setup='plug=3; r=range(1, 5)')  # plug in range
0.11037584743321105
>>> timeit.timeit('plug not in r', setup='plug=12; r=range(1, 5)')  # plug not in range
0.05579263413291358

这甚至没有考虑到创建range所花费的时间。

答案 1 :(得分:2)

这似乎也有效:

if not 2 < 3 < 4:
    print('3 is not between 2 and 4') # which it is, and you will not see this

if not 2 < 10 < 4:
    print('10 is not between 2 and 4')

原始问题的确切答案是if not 1 <= plug < 5:我猜

答案 2 :(得分:1)

使用:

if plug not in range(1,5):
     print "The number spider has disappeared down the plughole"

当变量插头超出范围1到5

时,它将打印给定的行

答案 3 :(得分:0)

if (int(5.5) not in range(int(3.0), int(6.9))):
    print('False')
else:
    print('True')

value应该以整数类型转换,否则not in range给出奇怪的结果。

答案 4 :(得分:-1)

if not plug in range(1,5):
     #bla