bisect.insort 在 Python 3 中的奇怪行为
Weird behaviour of bisect.insort in Python 3
Python 3.8.2
在 linux 框上,如果我创建一个 list
并在其上使用 insort
,我会得到预期的结果;另一方面,如果我在调用 insort
之前颠倒容器中元素的顺序,就会发生这种情况
>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a.reverse()
>>> a
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> bisect.insort(a,6)
>>> a
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 6]
我原以为 [9, 8, 7, 6, 6, 5, 4, 3, 2, 1, 0]
不是那样。
为什么会产生这个结果?
来自 docs:
This module provides support for maintaining a list in sorted
order without having to sort the list after each insertion.
也来自文档:
Unlike the sorted() function, it does not make sense for the bisect()
functions to have key or reversed arguments because that would lead to
an inefficient design (successive calls to bisect functions would not
“remember” all of the previous key lookups).
Python 3.8.2
在 linux 框上,如果我创建一个 list
并在其上使用 insort
,我会得到预期的结果;另一方面,如果我在调用 insort
之前颠倒容器中元素的顺序,就会发生这种情况
>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a.reverse()
>>> a
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> bisect.insort(a,6)
>>> a
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 6]
我原以为 [9, 8, 7, 6, 6, 5, 4, 3, 2, 1, 0]
不是那样。
为什么会产生这个结果?
来自 docs:
This module provides support for maintaining a list in sorted order without having to sort the list after each insertion.
也来自文档:
Unlike the sorted() function, it does not make sense for the bisect() functions to have key or reversed arguments because that would lead to an inefficient design (successive calls to bisect functions would not “remember” all of the previous key lookups).