2015-11-05 43 views
0

我正在使用這裏提到的二進制搜索功能:When are bisect_left and bisect_right not equal?,但不是返回False,我只想跳過不在列表e列表中的值。Python bisect:傳遞值而不是返回插入索引

from bisect import bisect_left 

def binsearch(l,e): 
    index = bisect_left(l,e) 
    if index == len(l) or l[index] != e: 
     return False 
    return index 

l = [1, 2, 3, 6, 7, 8, 9] 
e = [7, 9, 2, 4, 7] 
index = [] 

for i in e: 
    index.append(binsearch(l,i)) 

print index # [4, 6, 1, False, 4] 

我試圖取代return Falsepass但我得到的地方不在列表中的值會被索引。有沒有辦法簡單地傳遞一個值,如果它不在l和輸出[4, 6, 1, 4]

回答

1

如果用if語句中的pass替換return,就好像if不存在一樣。這就是爲什麼你得到一個索引返回。

您可以改爲返回一個標記值或一個元組,將索引與True/False /指示項目是否找到。

哨兵風格:

if index == len(l) or l[index] != e: 
    return -1 
return index 

元組風格:

if index == len(l) or l[index] != e: 
    return False, None 
return True, index 

要完成你需要把一些邏輯到您正在構建的最終名單現場圖片。元組形式的示例:

for i in e: 
    found, ind = binsearch(l,i) 
    if found: 
     index.append(ind) 
+0

完美。謝謝! – user2483176