如何使用Pythonic的方式搜索或操作已排序的序列(sequence)?
bisect
是标准库的一部分 - 这是否是你正在寻找的类型?
来自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:
import bisect
def find_in_sorted_list(elem, sorted_list):
# https://docs.python.org/3/library/bisect.html
'Locate the leftmost value exactly equal to x'
i = bisect.bisect_left(sorted_list, elem)
if i != len(sorted_list) and sorted_list[i] == elem:
return i
return -1
def in_sorted_list(elem, sorted_list):
i = bisect.bisect_left(sorted_list, elem)
return i != len(sorted_list) and sorted_list[i] == elem
L = ["aaa", "bcd", "hello", "world", "zzz"]
print(find_in_sorted_list("hello", L)) # 2
print(find_in_sorted_list("hellu", L)) # -1
print(in_sorted_list("hellu", L)) # False
sequence
(即Python 2.x中的“有七种序列类型:字符串,Unicode字符串,列表,元组,bytearrays,缓冲区和xrange对象。”)。 - Trevor Boyd Smith