# -*- 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)
- reversed() 返回一个反转迭代器:
# 这么看for循环只要是一个迭代器都可以 ?
>>> a = [1, 2, 3]
>>> b = reversed(a)
>>> print b
<listreverseiterator object at 0x7f961f3ecbd0>
>>> 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)
- bisect():
>>> import bisect
>>> dir(bisect)
['__builtins__', '__doc__', '__file__', '__name__', '__package__',
'bisect', 'bisect_left', 'bisect_right', 'insort', 'insort_left', 'insort_right']
使用这个模块的函数前先确保操作的列表是已排序的。
- bisect.insort 插入元素,返回None。改变了原有的序列。
>>> a = [3,5,7,9]
>>> c = bisect.insort(a,4)
>>>> print b
None
>>> a
[3, 4, 5, 7, 9]
- bisect.bisect 给出插入的位置(重复元素返回右插位置),即其目的在于查找该数值将会插入的位置并返回,而不会插入。
>>> a
[3, 4, 4, 5, 7, 9]
>>> d = bisect.bisect(a,4)
>>> d
3
- bisect_left 和 bisect_right 函数,该函数用入处理将会插入重复(不是重复也可以处理)数值的情况,返回将会插入的位置:
>>> a
[3, 4, 4, 5, 7, 9]
>>> bisect.bisect_right(a, 4)
3
>>> bisect.bisect_left(a, 4)
1
可见,单纯看其结果的话,两个函数的操作结果是一样的,其实插入的位置不同而已。

本文主要介绍了Python内置的bisect模块,包括bisect、bisect_left和bisect_right等函数的使用,强调了在操作前需要确保列表已排序。同时,通过示例展示了这些函数如何确定插入位置,特别是在处理重复元素时的区别。最后,提到了sys.argv[]参数自动转化为字符串的特点。

被折叠的 条评论
为什么被折叠?



