2010-07-07 91 views
16

是否有任何Python内建或广泛使用的Python库在排序序列中执行搜索?搜索排序列表?

+1

序列是什么?另外,什么样的搜索(二进制等)? – 2010-07-07 16:07:02

+0

我相信问题是试图成为“规范”或“通用”,因此“序列”的含义可能是使用[序列的Python文档定义(即Python 2.x)。有七种序列类型:字符串,Unicode字符串,列表,元组,字节数组,缓冲区和xrange对象。“)](https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple -bytearray-buffer-xrange) – 2017-10-25 12:42:51

回答

22

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

+0

没有解释如何搜索列表中的值。 – 2018-02-05 16:27:04

13

值得注意的是,有一些高质量的Python库可用于维护排序列表,这些列表还可实现快速搜索:sortedcontainersblist。当然,使用这些取决于您插入/移除列表中的元素并需要搜索的频率。每个模块都提供一个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模块的作者。