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

2024-06-01 06:35:00 发布

您现在位置: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"

返回同样的错误。


Tags: the代码innumberifnotrangespider
3条回答

使用:

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

当变量插头超出1到5的范围时,它将打印给定的行

如果您的范围有一个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:我想

相关问题 更多 >