检查两个列表中项目的近似外观-Python



我在写这个函数时,有两个由"1"one_answers"0"组成的列表,每次在list1中出现"1",我都必须检查list2中是否有与list1中的列表相距给定距离的"1"。

这是我做的函数,这样你就可以更好地理解:

for i in range (len(list1)):
if list1[i] == '1':
if any ('1' == num for num in list2[i:i+distance+1]): 
count += 1

我想知道是否有更快的方法可以做到这一点,或者从开始做一些事情

for '1' in list1:
if any etc.
indexes = [i for i,d in enumerate(list1) if d=='1']
distance = 2
count = 0
for i in indexes:
if '1' in list2[i:i+distance+1]:
count += 1

这个代码平均比你的快1.5-2倍。如果我们说大数组结果+答案较高的测试Res图像

这应该有效:

ones = [i for i,d in enumerate(list1) if d == '1']
cur = 0 # cursor pointing to the current one-location of list2 in the list "ones"
count = 0
for i in range(len(list1)):
if(list1[i] != '1'):
continue
# we will advance the cursor until it is past the lower bound of the selection
while(cur < len(ones) and ones[cur] < i - distance):
cur += 1
# if the cursor is out of bound we know that there are no more ones we are interested in inside list2 so we can exit the loop:
if(cur == len(ones)):
break
if(ones[cur] <= i + distance):
count += 1

注意:这种方法的性能仅取决于列表的大小,而不取决于距离变量

最新更新