首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >搜索排序列表?

搜索排序列表?
EN

Stack Overflow用户
提问于 2010-07-08 00:02:54
回答 3查看 31.9K关注 0票数 32

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-07-08 00:07:11

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

票数 28
EN

Stack Overflow用户

发布于 2014-04-18 03:22:23

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

来自SortedList的文档:

代码语言:javascript
复制
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模块的作者。

票数 21
EN

Stack Overflow用户

发布于 2018-03-14 23:27:10

Python:

代码语言:javascript
复制
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
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3196610

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档