hyytaojunming 发表于 2015-4-27 11:29:08

Python 中的bisect

  Python 中的bisect用于操作排序的数组,比如你可以在向一个数组插入数据的同时进行排序。下面的代码演示了如何进行操作:











import bisect
import random
random.seed(1)
print('New pos contents')
print('-----------------')
l=[]
for i in range(1,15):
r=random.randint(1,100)
position=bisect.bisect(l,r)
bisect.insort(l,r)
print '%3d %3d'%(r,position),l
  输出结果为:



New pos contents
-----------------
14   0
85   1
77   1
26   1
50   2
45   2
66   4
79   6
10   0
3   0
84   9
44   4
77   9
1   0
  
可以看到,在插入这些随机数的时候数组同时进行了排序。不过其中有一些重复的元素,比如上面的77,77。你可以对这些重复元素的顺序进行设置,如果希望重复的元素出现在与他相同的元素左边就是用bisect_left,否则就是用bisect_right,相应的使用insort_left和insort_right。比如下面的代码,我们可以看到出现重复的元素索引变化:
  



import bisect
import random
random.seed(1)
print('New pos contents')
print('-----------------')
l=[]
for i in range(1,15):
r=random.randint(1,100)
position=bisect.bisect_left(l,r)
bisect.insort_left(l,r)
print '%3d %3d'%(r,position),l
  输出结果为:



New pos contents
-----------------
14   0
85   1
77   1
26   1
50   2
45   2
66   4
79   6
10   0
3   0
84   9
44   4
77   8
1   0

  此函数bisect.bisect(list,key) ,犹如java里的TreeMap的tailMap(fromkey)
  
页: [1]
查看完整版本: Python 中的bisect