bisect模块

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



bisect.bisect( l , r) 假设列表l已排序,返回元素r可以插入在列表l的索引位置



bisect.insort(l,i) 假设l是有序的列表,插入i,并保持最新的列表有序排列


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 [ 14 ]
  85   1 [ 14 , 85 ]
  77   1 [ 14 , 77 , 85 ]
  26   1 [ 14 , 26 , 77 , 85 ]
  50   2 [ 14 , 26 , 50 , 77 , 85 ]
  45   2 [ 14 , 26 , 45 , 50 , 77 , 85 ]
  66   4 [ 14 , 26 , 45 , 50 , 66 , 77 , 85 ]
  79   6 [ 14 , 26 , 45 , 50 , 66 , 77 , 79 , 85 ]
  10   0 [ 10 , 14 , 26 , 45 , 50 , 66 , 77 , 79 , 85 ]
   3   0 [ 3 , 10 , 14 , 26 , 45 , 50 , 66 , 77 , 79 , 85 ]
  84   9 [ 3 , 10 , 14 , 26 , 45 , 50 , 66 , 77 , 79 , 84 , 85 ]
  44   4 [ 3 , 10 , 14 , 26 , 44 , 45 , 50 , 66 , 77 , 79 , 84 , 85 ]
  77   9 [ 3 , 10 , 14 , 26 , 44 , 45 , 50 , 66 , 77 , 77 , 79 , 84 , 85 ]
   1   0 [ 1 , 3 , 10 , 14 , 26 , 44 , 45 , 50 , 66 , 77 , 77 , 79 , 84 , 85 ]

 


可以看到,在插入这些随机数的时候数组同时进行了排序。不过其中有一些重复的元素,比如上面的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 [ 14 ]
  85   1 [ 14 , 85 ]
  77   1 [ 14 , 77 , 85 ]
  26   1 [ 14 , 26 , 77 , 85 ]
  50   2 [ 14 , 26 , 50 , 77 , 85 ]
  45   2 [ 14 , 26 , 45 , 50 , 77 , 85 ]
  66   4 [ 14 , 26 , 45 , 50 , 66 , 77 , 85 ]
  79   6 [ 14 , 26 , 45 , 50 , 66 , 77 , 79 , 85 ]
  10   0 [ 10 , 14 , 26 , 45 , 50 , 66 , 77 , 79 , 85 ]
   3   0 [ 3 , 10 , 14 , 26 , 45 , 50 , 66 , 77 , 79 , 85 ]
  84   9 [ 3 , 10 , 14 , 26 , 45 , 50 , 66 , 77 , 79 , 84 , 85 ]
  44   4 [ 3 , 10 , 14 , 26 , 44 , 45 , 50 , 66 , 77 , 79 , 84 , 85 ]
  77   8 [ 3 , 10 , 14 , 26 , 44 , 45 , 50 , 66 , 77 , 77 , 79 , 84 , 85 ]
   1   0 [ 1 , 3 , 10 , 14 , 26 , 44 , 45 , 50 , 66 , 77 , 77 , 79 , 84 , 85 ]

 

此函数bisect.bisect(list,key) ,犹如java里的TreeMap的tailMap(fromkey)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值