Python 搜索已排序的列表?

Python 搜索已排序的列表?,python,search,sorting,Python,Search,Sorting,什么是Python式的搜索或操作排序的方法?是标准库的一部分-这就是您正在寻找的类型吗?值得注意的是,有两个高质量的Python库用于维护排序列表,它们也实现了快速搜索:和。使用这些当然取决于您从列表中插入/删除元素以及需要搜索的频率。这些模块中的每一个都提供了一个类,可以有效地按照排序顺序维护项目 从SortedList的文档中: L.bisect_left(value) Similar to the bisect module in the standard library, thi

什么是Python式的搜索或操作排序的方法?

是标准库的一部分-这就是您正在寻找的类型吗?

值得注意的是,有两个高质量的Python库用于维护排序列表,它们也实现了快速搜索:和。使用这些当然取决于您从列表中插入/删除元素以及需要搜索的频率。这些模块中的每一个都提供了一个类,可以有效地按照排序顺序维护项目

从SortedList的文档中:

L.bisect_left(value)
    Similar to the bisect module in the standard library, this returns
    an appropriate index to insert value in L. If value is already present
    in L, the insertion point will be before (to the left of) any existing
    entries.

L.bisect(value)
    Same as bisect_left.

L.bisect_right(value)
    Same as bisect_left, but if value is already present in L, the
    insertion point will be after (to the right of) any existing entries.
这两种实现都使用二进制搜索来查找给定值的正确索引。有一个页面可以在两个模块之间进行选择

免责声明:我是sortedcontainers模块的作者。

Python:

def find_elem_in_sorted_list(elem, sorted_list):
    # https://docs.python.org/3/library/bisect.html
    'Locate the leftmost value exactly equal to x'
    i = bisect_left(sorted_list, elem)
    if i != len(sorted_list) and sorted_list[i] == elem:
        return i
    return -1

什么顺序?还有,什么样的搜索(二进制等)?我相信问题是试图“规范”或“通用”,因此“序列”的含义可能是使用了,它没有解释如何搜索列表中的值函数对于查找插入点很有用,但用于普通搜索任务可能会很棘手或尴尬。”@Martin先生在排序列表中查找插入点与在排序列表中执行“普通搜索任务”有什么区别?@theonlygusti我相信关键是可能需要帮助函数,这种搜索通常需要找到所有匹配项,而不仅仅是第一个匹配项