bisect二分查找模块使用

import bisect
L = [1, 3, 3, 6, 8, 12, 15]
x = 5
x_insert_point = bisect.bisect_left(L, x)# 在L中查找x,x存在时返回x左侧的位置,x不存在返回应该插入的位置..这是3存在于列表中,返回左侧位置1
print(x_insert_point)
x_insert_point = bisect.bisect_right(L, x) # 在L中查找x,x存在时返回x右侧的位置,x不存在返回应该插入的位置..这是3存在于列表中,返回右侧位置3
print(x_insert_point)
x_insort_left = bisect.insort_left(L, x) # 将x插入到列表L中,x存在时插入在左侧
print(L)
x_insort_rigth = bisect.insort_right(L, x) # 将x插入到列表L中,x存在时插入在右侧    
print(L)

二分法的实现方式
def binary_search(t,x):
temp = t;
temp.sort();
low = 0;
mid = 0;
high = len(temp)-1;
while low < high:
mid = (low+high)/2;
if x<t[mid]:
high = mid-1;
elif x>t[mid]:
low = mid+1;
else:
return mid-1; #是否等价与bisect_left;


可以用于查找:

有两个文件,每个都有很多行ip地址,求出两个文件中相同的ip地址:

复制代码
# coding:utf-8
import bisect

with open('test1.txt', 'r') as f1:
list1 = f1.readlines()
for i in range(0, len(list1)):
list1[i] = list1[i].strip('\n')
with open('test2.txt', 'r') as f2:
list2 = f2.readlines()
for i in range(0, len(list2)):
list2[i] = list2[i].strip('\n')

list2.sort()
length_2 = len(list2)
same_data = []
for i in list1:
pos = bisect.bisect_left(list2, i)
if pos < len(list2) and list2[pos] == i:
same_data.append(i)
same_data = list(set(same_data))
print(same_data)
posted @ 2018-07-18 11:45  yoyo008  阅读(188)  评论(0编辑  收藏  举报