# -*- coding:utf-8 -*-
import bisect
import sys
HAYSTACK = [1, 4, 5, 6, 8, 12, 15, 20, 21, 23, 23, 26, 29,30]
NEEDLES = [0, 1, 2, 5, 8, 10, 22, 23, 29, 30, 31]
ROW_FMT = '{0:2d} @ {1:2d} {2}{1:<2d}'
def demo(bisect_sn):
for needle in reversed(NEEDLES):
position = bisect_sn(HAYSTACK, needle)
offset = position * ' |'
print ROW_FMT.format(needle, position, offset)
if __name__ == '__main__':
if sys.argv[-1] == 'left':
bisect_fn = bisect.biset_left
else:
bisect_fn = bisect.bisect
print'DEMO: ', bisect_fn.__name__
# '%2d' % n 相当于一个整体
print'haystack ->', ' '.join('%2d' % n for n in HAYSTACK)
demo(bisect_fn)
# 这么看for循环只要是一个迭代器都可以 ?
>>> a = [1, 2, 3]
>>> b = reversed(a)
>>> print b
>>> list(b)
[3, 2, 1]
2.format():
# 前面的0: 1: 2: 是对应a,b,c 。2d是指占位2个长度的整形。
# <, >, ^, 分别是向左向右向中对齐。
ROW_FMT = '{0:2d} @ {1:2d} {2}{1:<2d}'.format(a, b ,c)
>>> import bisect
>>> dir(bisect)
['__builtins__', '__doc__', '__file__', '__name__', '__package__',
'bisect', 'bisect_left', 'bisect_right', 'insort', 'insort_left', 'insort_right']
使用这个模块的函数前先确保操作的列表是已排序的。
>>> a = [3,5,7,9]
>>> c = bisect.insort(a,4)
>>>> print b
None
>>> a
[3, 4, 5, 7, 9]
>>> a
[3, 4, 4, 5, 7, 9]
>>> d = bisect.bisect(a,4)
>>> d
3
>>> a
[3, 4, 4, 5, 7, 9]
>>> bisect.bisect_right(a, 4)
3
>>> bisect.bisect_left(a, 4)
1
可见,单纯看其结果的话,两个函数的操作结果是一样的,其实插入的位置不同而已。