将Python列表排成一行并找到索引

时间:2013-10-04 13:20:48

标签: python list bisection

当我使用bisect_left()函数时,为什么我没有得到元素的index,而是index + 1

import bisect

t3 = ['carver', 'carvers', 'carves', 'carving', 'carvings']
print bisect.bisect(t3, 'carves')    # 3
print bisect.bisect(t3, 'carving')   # 4
print bisect.bisect(t3, 'carver')    # 1

1 个答案:

答案 0 :(得分:23)

bisect.bisect()bisect.bisect_right()的简称,不是 bisect.bisect_left()

您需要使用全名bisect.bisect_left(),而不是:

>>> import bisect
>>> t3 = ['carver', 'carvers', 'carves', 'carving', 'carvings']
>>> bisect.bisect(t3, 'carves')
3
>>> bisect.bisect_left(t3, 'carves')
2
>>> bisect.bisect == bisect.bisect_right
True
>>> bisect.bisect == bisect.bisect_left
False