[英]Finding List A item pattern search in List B
我正在使用搜索模式算法在 txt(list) 中查找 pat(list) 項。 這個 function 應該返回列表 txt 的索引值。
def search(pat, txt):
M = len(pat)
N = len(txt)
# A loop to slide pat[] one by one */
for i in range(N - M + 1):
j = 0
# For current index i, check
# for pattern match */
while(j < M):
if (txt[i + j] != pat[j]):
break
j += 1
if (j == M):
print("Pattern found at index ", i)
# Driver's Code
txt = ["GA","07","09","07","0H"]
pat = ["GA","09","0H"]
for i in pat:
for y in txt:
if i == y:
if __name__ == '__main__':
# Function call
search(pat, txt)
我已經修改了上面的代碼。 但這不起作用。 但是,在原始代碼中,如果提供一項來拍它,它會起作用,如果提供多於一項來拍,它就會崩潰並且不顯示任何內容。 這是原始代碼。
# Python3 program for Naive Pattern
# Searching algorithm
def search(pat, txt):
M = len(pat)
N = len(txt)
# A loop to slide pat[] one by one */
for i in range(N - M + 1):
j = 0
# For current index i, check
# for pattern match */
while(j < M):
if (txt[i + j] != pat[j]):
break
j += 1
if (j == M):
print("Pattern found at index ", i)
# Driver's Code
if __name__ == '__main__':
txt = ["GA","07","09","07","0H"]
pat = ["07"]
# Function call
search(pat, txt)
請提供不止一項來拍(列出)並執行。 我需要這個朴素的搜索模式算法來查找 txt(list) 中的所有 pat(list) 項目並返回索引。 例如
pat = ["GA","09","0H"]
如果要獲取索引和項目:
[list(filter(lambda item: item[1] == pat_item, enumerate(txt)))[0] for pat_item in pat]
output:
[(0, 'GA'), (2, '09'), (4, '0H')]
如果您只想獲取索引:
[list(filter(lambda item: item[1] == pat_item, enumerate(txt)))[0][0] for pat_item in pat]
output:
[0, 2, 4]
嘗試這個:
indices = []
for x in pat:
try:
indices.append(txt.index(x))
except ValueError:
pass
txt = ['GA', '07', '09', '07', '0H']
和pat = ['GA', '09', '0H']
:
>>> indices
[0, 2, 4]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.