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

Pet*_*ter -3 python range

好的,所以我现在有Python代码,它做了这样的事情:

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

但我真正想要做的是检查的数量并不在范围内.我用Google搜索并查看了Python文档但我找不到任何内容.有任何想法吗?

附加数据:运行此代码时:

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

我收到以下错误:

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

我也尝试过:

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

哪个返回了相同的错误.

Mar*_*nen 18

如果您的范围step是1,那么使用它的性能要快得多:

if not 1 <= plug < 5:
Run Code Online (Sandbox Code Playgroud)

比使用not他人建议的方法更好:

if plug not in range(1, 5)
Run Code Online (Sandbox Code Playgroud)

证明:

>>> 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
Run Code Online (Sandbox Code Playgroud)

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


Ebr*_*owi 6

这似乎也有效:

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')
Run Code Online (Sandbox Code Playgroud)

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