![](/img/trans.png)
[英]Partial match between two python lists, one list exactly present in the other with few additional characters in Python
[英]Do two boolean colums/lists match? Comparison of two different sized colums: Does a part of one list match a part of the other? (python)
我有不同長度的 boolean 值的不同列表,我將其稱為blists
,我想將其與固定的 boolean 列表進行比較,我將其稱為blist
。
目標是在blist
的列表( blists
)中找到最長的匹配系列。
我想看看是否可以在blists
列表的某處找到部分甚至整個blist
列表。 我會設置一個最小匹配值,以免我的 output 溢出。
例如(真 = T,假 = F,示例比現實生活中短):
List 1 of blists: (T,T,T,F,T,T,F,F,F,T)
blist: (F,F,T,T,F,F,F,F)
我想看看列表 1 (F,T,T,F,F,F)
的一部分是否等於列表blist
的某些部分。 因此,對於(F,F,T,T,F,F,F,F)
的示例 blist,output 應該是,列表 1 的一部分可以在blist
中找到。
以 output 為例:
blist
與列表 1 相似 ((list 1 中的起點) 3, ( blist
中的起點) 1, (length) 6, (匹配的部分列表): (F,T,T,F,F,F)
我嘗試.corr()
等, for
-loops 和if
-conditions 並且沒有任何東西想要正常工作。
這個問題可能有一個簡單的解決方案,但我無法弄清楚。
如果您想要一個實現來確定公共列表在每個列表的確切位置,這里是一個簡單的“for循環”實現(為了便於閱讀,我使用“0,1”而不是“True and False”。你可以轉換它容易地):
a = [0,1,0,1,1,0,0,1,0,1,1,1,0,1,1,1,0,0]
b = [1,1,1,1,1,0,1,1,1,0,0,0,1,1]
list1_start = 0
list2_start = 0
common_list = []
for i in range(len(a)):
for j in range(len(a)-i):
for i2 in range(len(b)):
for j2 in range(len(b)-i2):
if a[i:i+j] == b[i2:i2+j2]:
if len(common_list)<len(a[i:i+j]):
common_list = a[i:i+j]
list1_start = i+1
list2_start = i2+1
print("list1 start: ", list1_start)
print("list2 start: ", list2_start)
print("common_list: ",common_list)
答案:
list1 start: 10
list2 start: 3
common_list: [1, 1, 1, 0, 1, 1, 1, 0]
一種方法是將列表加入字符串並使用“in”和“find”字符串方法和循環:
l1 = ['T','T','T','F','T','T','F','F','F','T']
blist = ['F','F','T','T','F','F','F','F']
w1, bw = ''.join(l1), ''.join(blist)
all_options = sum([[w1[i:ii] for i in range(len(w1))] for ii in range(len(w1))], [])
all_valid_options = [x for x in all_options if (len(x)>1 and x in bw)]
longest_option = sorted(all_valid_options, key=len)[-1]
w1_start = w1.find(longest_option)
w1_end = w1_start + len(longest_option)
bw_start = bw.find(longest_option)
bw_end = bw_start + len(longest_option)
print(longest_option, len(longest_option), (w1_start, w1_end), (bw_start, bw_end))
FTTFFF 6 (3, 9) (1, 7)
我建議使用類似KMP 算法的方法來匹配整個列表中的子集列表。 它將利用 O(n) 復雜度。 使一個完整的實現使用最壞的 O(n^3),但很可能是 O(n^2)。 解決方案可能如下所示:
longest_match = []
for i in range(len(blists)):
if(i+len(longest_match) >= len(blists):
break
for j in range(i+len(longest_match)+1, len(blists)):
if(KMPSearch(blists[i,j], blist)):
longest_match = blists[i,j]
else:
break
在列表中循環遍歷每個 position 並檢查從 i 開始的子集列表,並超過已找到的最長匹配的長度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.