【发布时间】:2015-11-05 13:20:47
【问题描述】:
我正在使用这里提到的二进制搜索功能:When are bisect_left and bisect_right not equal?,但我不想返回 False,我只想跳过不在列表 e 中的值。
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]
我尝试用pass 替换return False,但我得到了不在列表中的值的放置位置的索引。如果值不在l 中,有没有办法简单地传递一个值并输出[4, 6, 1, 4]?
【问题讨论】:
标签: python python-2.7