Python-二进制搜索以查找与索引匹配的列表元素?

时间:2020-07-08 21:48:07

标签: python python-3.x list binary-search

因此,我想使用二进制搜索来搜索列表,并查找具有与索引号匹配的值的列表元素。例如,如果我的列表在索引2处包含2,我想打印该值。它也必须使用多个值。到目前为止,这是我进行二分搜索的结果:

alist=[4,5,7,9,13,45,34,58,99,125,145]
key=145
"""Search key in alist[start... end - 1]."""
start = 0
end = len(alist)
while start < end:
    mid = (start + end)//2
    if alist[mid] > key:  # this is where we check if the guess is bigger than the key
            end = mid
    elif alist[mid] < key:
            start = mid + 1
    elif alist[mid] == key:
                print (f"you searched for {alist[mid]} and we found it in the index number {alist.index(125)} of the list")
                break
else:
    print ("Not Found!")

这仅适用于钥匙。我是python的新手,想知道如何实现它。

2 个答案:

答案 0 :(得分:0)

如果我对您的理解正确,我认为这应该适用于您的打印声明:

print("you searched for {} and we found it in the index number {} of the list".format(key, mid))

如果只想在索引与值相同时打印它,则只需添加一个if语句:

if key == mid:
    print("you searched for {} and we found it in the index number {} of the list".format(key, mid))

这能回答您的问题吗?

答案 1 :(得分:0)

如果我正确地理解了您的问题,那么您想查找与其索引号具有相同值的元素,那么您就必须遍历列表并使用条件打印这些元素 print([i for i in alist if i==alist.index(i)])