簡體   English   中英

找到兩個排序列表中是否存在數字的更好方法

[英]Better way to find if a number is present in between two numbers of a sorted list

我有一個像這樣的排序列表

s = [1 , 4 ,6 , 9  ,10 ]

我想知道列表中是否存在數字,或者兩個數字之間是否存在數字。 如果它出現在兩個數字之間,我想打印出來。

現在我的代碼看起來像這樣

for x in s:
   if b == x: \\ b is the number
       print b
   elif b > x and b < s[s.index(x) + 1] and s.index(x) < len(s):
       print b , s[s.index(x) + 1]

有沒有更好的方法呢?

bisect模塊正是這樣做的:

s = [1 , 4 ,6 , 9  ,10 ]
import bisect

x = 5
n = bisect.bisect_left(s, x)
if s[n:n+1] == [x]:
    print x, 'is in the list'
else:
    print x, 'comes between', s[n-1:n], 'and', s[n:n+1]

這不是完美優化,但您可以避免多次使用index()方法!

for i,j in enumerate(s,1):
 if b == j: \\ b is the number
   print b
 elif b > j and b < s[i+1] and s[i] < len(s):
   print b , s[i + 1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM