简体   繁体   English

如何在严格增加的python列表中有效查找元素的序数?

[英]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. 我只能想到遍历该列表,但这效率很低,因为该列表可以增长到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. 我想知道是否有任何内置的python函数可以有效地做到这一点。

Take a look at the bisect module. 看一看bisect模块。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM