繁体   English   中英

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

[英]Checking if a number is not in range in Python

我目前有 Python 代码,它执行以下操作:

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

但我实际上想检查数字是否不在范围内。 我已经用谷歌搜索并查看了 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"

哪个返回了相同的错误。

如果您的范围有一个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所花费的时间。

这似乎也有效:

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: ,我猜对原始问题的确切答案是。

利用:

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

只要变量plug超出 1 到 5 的范围,它将打印给定的行。

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

该值应强制转换为整数,否则not in range会产生奇怪的结果。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM