搜索排序列表?

时间:2010-07-07 16:02:54

标签: python search sorting

什么是Pythonic搜索或操作已排序sequence的方法?

3 个答案:

答案 0 :(得分:24)

bisect是标准库的一部分 - 那是你要找的东西吗?

答案 1 :(得分:14)

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

来自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.

两种实现都使用二进制搜索来查找给定值的正确索引。在performance comparison页面中有两个模块可供选择。

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

答案 2 :(得分:-1)

的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