python在列表中查找指定元素下标值

 不过还是不太明白二分法中return

list1=[1,3,5,6,7,8,9,10]

#二分查找
def search(x,list1):
    l=len(list1)
    left=0
    right=l-1
    while left<=right:
        middle=(left+right)//2
        if list1[middle]==x:
            return middle
        elif list1[middle]>x:
            right=middle-1
        else:
            left=middle+1
        return middle
n=3
print(search(n,list1))

#另一种方法
def search1(x,list1):
    m=0
    for i in list1:
        if i == x:
            break
    m=m+1
    return m

n=3
print(search1(n,list1))

 

你可能感兴趣的:(python在列表中查找指定元素下标值)