我试图理解这段代码:
i = bisect.bisect(self.A, [id + 1]) - 1
在这里,开发人员传入[id + 1]
了bisect()
as x
(目标值)。在Python 文档及其bisect 的源代码中,我没有看到任何提到的x
可以是长度为 1 的数组的地方。
代码的目标是查找A
具有id
或最大 id in的元组的值A
。例如:
A = [[0, 0], [2, 4]]
id = 1
Output = 0 // Here: 1 isn't in A so return value 0 from id 0 which is the biggest id < input id
A = [[0, 0], [2, 4], [3, 12]]
id = 3
Output = 12 // 3 is in A so return 12
我尝试取出ids
以尝试查找该值,但我的代码返回错误答案:
A = [[0, 0], [2, 4]]
id = 1
ids = [0, 2]
i = bisect.bisect(ids, id) // return 1 which is correct for bisect but not the expected result
i = bisect.bisect(ids, id + 1) - 1 // still returns 1
i = bisect.bisect_left(ids, id + 1) - 1 // still returns 1
i = bisect.bisect_left(ids, id + 1) - 1 // returns 0
但是,bisect_left()
将返回错误的答案:
A = [[0, 0], [2, 4], [3, 12]]
id = 3
i = bisect.bisect(self.A, [id + 1]) - 1 // returns 12 which is correct
ids = [0, 2, 3]
i = bisect.bisect_left(ids, id + 1) - 1 // returns 4
那么为什么会有区别呢?传递是如何[x]
工作的?