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)

转载于:https://www.cnblogs.com/yoyo008/p/9328340.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值