【发布时间】:2011-03-12 21:58:39
【问题描述】:
什么是搜索或操作已排序sequence 的 Pythonic 方式?
【问题讨论】:
-
序列是什么?另外,什么样的搜索(二进制等)?
什么是搜索或操作已排序sequence 的 Pythonic 方式?
【问题讨论】:
bisect 是标准库的一部分 - 这是您要寻找的东西吗?
【讨论】:
值得注意的是,有几个用于维护排序列表的高质量 Python 库也实现了快速搜索:sortedcontainers 和 blist。使用这些当然取决于您从列表中插入/删除元素以及需要搜索的频率。这些模块中的每一个都提供了一个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 模块的作者。
【讨论】:
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
【讨论】: