insort_left 和 insort_right 在 bisect 中有什么区别?

mya*_*sev 6 python

为什么都insort_leftinsort_right存在; 由于元素相等,结果不总是相同的吗?

>>> import bisect
>>> foo = [1,2,3]
>>> 
>>> bisect.insort_left(foo, 1)
>>> foo
[1, 1, 2, 3]
>>> 
>>> bisect.insort_right(foo, 1)
>>> foo
[1, 1, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)

Tim*_*ers 9

对于大多数目的,结果是无法区分的,但在某些情况下它可能很重要,尤其是在使用可选key=参数时。

您是否了解保证或不保证“稳定”的排序算法之间的区别?如果没有,请单击链接;-)

ys = []
for x in xs:
    bisect.insort_right(ys, x)
Run Code Online (Sandbox Code Playgroud)

填充ys了一种稳定的xs条目,但使用insort_left()不会。


wja*_*rea 6

对象可以是等价的,而不是完全相同的。

>>> bisect.insort_left(foo, 1.0)
>>> foo
[1.0, 1, 1, 1, 2, 3]
>>> 
>>> bisect.insort_right(foo, 1.0)
>>> foo
[1.0, 1, 1, 1, 1.0, 2, 3]
Run Code Online (Sandbox Code Playgroud)