【问题标题】:How to find an index at which a new item can be inserted into sorted list and keep it sorted?如何找到可以将新项目插入排序列表并保持排序的索引?
【发布时间】:2012-07-02 16:42:00
【问题描述】:
a = 132

b = [0, 10, 30, 60, 100, 150, 210, 280, 340, 480, 530]

我想知道a应该在有序列表b中的第6位。

最pythonic的方法是什么?

【问题讨论】:

  • a 实际上将在b 中位于第 6 位,而不是第 4 位。正如@madjar 所说,使用了bisect 模块。 bisect.bisect(b, a) 获取位置(或bisect_[left|right])并用于插入bisect.insort(b, a)insort[left|right]

标签: python sortedlist


【解决方案1】:

bisect 是 Python 标准库中的一个模块,非常适合此任务。模块 bisect 中的函数 bisect 将为您提供值的插入点的索引。

让我举一个bisect的代码示例

from bisect import bisect
a = 132
b = [0, 10, 30, 60, 100, 150, 210, 280, 340, 480, 530]
print(bisect(b, a))

结果将是5,因为列表是从0开始的,所以实际上是第6位。

您可以知道的是将结果用于insert

index = bisect(b, a)
b.insert(index, a)

或者没有中间变量

b.insert(bisect(b, a), a)

现在b 将是[0, 10, 30, 60, 100, 132, 150, 210, 280, 340, 480, 530]

【讨论】:

  • 如果 a 是对象或字典而 b 是对象或字典的排序列表怎么办?
【解决方案2】:

使用bisect。它不是最漂亮的 API,但正是您所需要的。

你会想要使用bisect.bisect,它会返回你想要的。

【讨论】:

  • 为什么它不是“最漂亮的 API”?
【解决方案3】:

还有更多关于边缘情况的担忧。例如,假设您要在(a, c) 范围内选择上述b 中的元素,然后使用

b[idx_a:idx_c]

那么您需要考虑a, c 实际上是b 的元素的情况。请注意

bisect.bisect(b, 10)
bisect.bisect(b, 11)

两者都会给出索引 2。因此,如果 a=10 我们需要将索引降低 1。幸运的是,有一个函数 bisect.bisect_left 可以做到这一点,即在我们的示例中

bisect.bisect_left(b, 10)

给出 1。

总体而言,左索引应使用bisect.bisect_left() 和右索引bisect.bisect_right() 计算(与bisect.bisect() 相同)。

【讨论】:

    猜你喜欢
    • 2013-11-28
    • 1970-01-01
    • 2017-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 2011-12-22
    • 1970-01-01
    相关资源
    最近更新 更多