insort_left和insort_right在bisect中有什么区别?
为什么都insort_left和insort_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]
回答
对于大多数目的,结果是无法区分的,但在某些情况下它可能很重要,尤其是在使用可选key=参数时。
您是否了解保证或不保证“稳定”的排序算法之间的区别?如果没有,请单击链接;-)
ys = []
for x in xs:
bisect.insort_right(ys, x)
填充ys了一种稳定的xs条目,但使用insort_left()不会。
回答
对象可以是等价的,而不是完全相同的。
>>> 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]
THE END
二维码