data_list = [
{"id": 1,},
{"id": 2,},
{"id": 3,},
{"id": 4,},
{"id": 5,},
{"id": 6,},
]
如上所示,我有一个字典列表。我想删除ID为4的字典,而不使用线性搜索。
答案 0 :(得分:1)
由于您说的是顺序,所以我会执行二进制搜索
def bsearch(data_list,x):
lo,hi=0,len(data_list)-1
while lo<=hi:
mid=(lo+hi)//2
if data_list[mid]["id"]==x:
return mid
if data_list[mid]["id"]>x:
hi=mid-1
elif data_list[mid]["id"]<x:
lo=mid+1
return -1
data_list = [
{"id": 1,},
{"id": 2,},
{"id": 3,},
{"id": 4,},
{"id": 5,},
{"id": 6,},
]
idx=bsearch(data_list,4)
if idx:
data_list.pop(idx)
else:
print("value not found")
print(data_list)