Checking if a number is not in range in Python

僤鯓⒐⒋嵵緔 提交于 2020-01-01 07:25:05

问题


Ok, so I have Python code at the moment which does something like this:

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

But what I actually want to do is check if the number is not in range. I've googled and had a look at the Python docs but I can't find anything. Any ideas?

Additional data: When running this code:

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

I get the following error:

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

I also tried:

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

Which returned the same error.


回答1:


If your range has a step of one, it's performance-wise much faster to use:

if not 1 <= plug < 5:

Than it would be to use the not method suggested by others:

if plug not in range(1, 5)

Proof:

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

And this is not even taking into account the time spent on creating the range.




回答2:


This seems work as well:

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

Exact answer to the original question would be if not 1 <= plug < 5: I guess




回答3:


Use:

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

It will print given line whenever variable plug is out of range 1 to 5




回答4:


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

value should type casting in integer, otherwise not in range gives strange result.




回答5:


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


来源:https://stackoverflow.com/questions/36507957/checking-if-a-number-is-not-in-range-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!