【问题标题】:Searching a sorted list? [closed]搜索排序列表? [关闭]
【发布时间】:2011-03-12 21:58:39
【问题描述】:

什么是搜索或操作已排序sequence 的 Pythonic 方式?

【问题讨论】:

标签: python search sorting


【解决方案1】:

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

【讨论】:

  • 这并没有解释如何在列表中搜索值。
  • 从您提供的链接中:“bisect() 函数对于查找插入点很有用,但对于常见的搜索任务可能会很棘手或尴尬。”
  • @MrMartin 在排序列表中查找插入点与在排序列表中执行“常见搜索任务”有什么区别?
  • @theonlygusti 我认为关键是可能需要辅助函数,并且搜索通常需要找到所有匹配项,而不仅仅是第一个
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    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
    

    【讨论】:

      猜你喜欢
      • 2013-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-23
      • 2013-03-06
      • 2019-08-31
      • 1970-01-01
      • 2021-12-12
      相关资源
      最近更新 更多