首页 > 其他 > 详细

bisect二分查找模块使用

时间:2018-07-18 13:15:24      阅读:162      评论:0      收藏:0      [点我收藏+]
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)

bisect二分查找模块使用

原文:https://www.cnblogs.com/yoyo008/p/9328340.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!