Python bisect 模块简介

2011-12-30

最近在看 hash_ring 的实现代码. 看到 一个 python 模块 bisect 不明白 什么 意思: 于是 就 google 了下 Python 中的bisect用于操作排序的数组,比如你可以在向一个数组插入数据的同时进行排序。

#!/usr/bin/python

import bisect    
import random
    
data = list()
    
for i in range( 1, 20):
    rand = random.randint(1,100)
    position = bisect.bisect(list, rand)
    bisect.insort(data, rand)
    print '%3d%3d'%(rand, position), list

输出结果:

    23  0 [23]
     31  1 [23, 31]
      1  0 [1, 23, 31]
     15  1 [1, 15, 23, 31]
     61  4 [1, 15, 23, 31, 61]
     28  3 [1, 15, 23, 28, 31, 61]
     42  5 [1, 15, 23, 28, 31, 42, 61]
     70  7 [1, 15, 23, 28, 31, 42, 61, 70]
     97  8 [1, 15, 23, 28, 31, 42, 61, 70, 97]
     77  8 [1, 15, 23, 28, 31, 42, 61, 70, 77, 97]
     61  7 [1, 15, 23, 28, 31, 42, 61, 61, 70, 77, 97]
     79 10 [1, 15, 23, 28, 31, 42, 61, 61, 70, 77, 79, 97]
     47  6 [1, 15, 23, 28, 31, 42, 47, 61, 61, 70, 77, 79, 97]
      1  1 [1, 1, 15, 23, 28, 31, 42, 47, 61, 61, 70, 77, 79, 97]
     37  6 [1, 1, 15, 23, 28, 31, 37, 42, 47, 61, 61, 70, 77, 79, 97]
     84 14 [1, 1, 15, 23, 28, 31, 37, 42, 47, 61, 61, 70, 77, 79, 84, 97]
     52  9 [1, 1, 15, 23, 28, 31, 37, 42, 47, 52, 61, 61, 70, 77, 79, 84, 97]
     66 12 [1, 1, 15, 23, 28, 31, 37, 42, 47, 52, 61, 61, 66, 70, 77, 79, 84, 97]
     77 15 [1, 1, 15, 23, 28, 31, 37, 42, 47, 52, 61, 61, 66, 70, 77, 77, 79, 84, 97]

list 的输出结果 自动升序.

参考文档: <http://docs.python.org/library/bisect.html>