当前位置: 动力学知识库 > 问答 > 编程问答 >

How to efficiently find the ordinal number of an element in a strictly increasing python list?

问题描述:

I can only think of iterating through the list, but that's highly inefficient as the list can grow as big as 1000000.

EDIT: I also know about binary search. I would like to know if there is any builtin python function which can do this efficiently.

网友答案:

Take a look at the bisect module. The docs suggest the following for locating an element in a sorted list:

def index(a, x):
    'Locate the leftmost value exactly equal to x'
    i = bisect_left(a, x)
    if i != len(a) and a[i] == x:
        return i
    raise ValueError
分享给朋友:
您可能感兴趣的文章:
随机阅读: