[英]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.