2010-07-07 110 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模塊的作者。