【问题标题】:Python bisect: pass value instead of returning insertion indexPython bisect:传递值而不是返回插入索引
【发布时间】: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


    【解决方案1】:

    如果在if 语句中将return 替换为pass,就好像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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 2012-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多