簡體   English   中英

列表模式檢查

[英]List pattern Check

我想解決一個與列表模式相關的問題。 我有一個模式列表pattern=['A', 'B']和一個實際列表Actual =['A','B','A','B',A'] ,我需要檢查that** 實際列表** 元素是否遵循模式列表的模式

條件1:

let say if Actual=['A','B','A','B','A']
and pattern=['A','B']
if this condition then i will receive in print **yes Actual list follow the pattern of pattern list**
But if Actual==['A','B','A','B','B']
then return **not matching with the pattern of pattern list and Capture the not matching postion and not matching Element of Actual list**.

Similarly for the other repetition of pattern like in condition 2.

Condition 2:
Actual=['X','Y','Z',X','Y']
pattern=['X','Y','Z']
if this condition then i will receive in print **yes Actual list follow the pattern of pattern list**.

but if Actual=['X','Y','Z','Y','Z']
pattern=['X','Y','Z']
if this the then return **not matching with the pattern of pattern list and Capture the not matching postion and not matching Element of Actual list**.

and many more like this.

我試過使用:

if Actual==pattern*int(len(Actual)/(len(Pattern))
    return True
else:
    #Capturing the misplace postion in the Actual list.

但只有當實際列表的兩個長度都是模式的除數時,以上一個才有效。

任何人都可以建議我任何其他方法嗎?

注意:模式列表的長度可能會有所不同。它並不總是像上述情況那樣為 2。

這可以使用itertools以一種相當酷的方式解決

from itertools import cycle, count

def f(actual,pattern):
    return all( a==b for a,b in zip(actual,cycle(pattern))) 

def mismatch(actual, pattern):
    return ( c for a,b,c in zip(actual,cycle(pattern),count()) if a != b)




#Some tests    
assert f(['A','B','A','B','A'],['A','B']) 
assert not f(['A','B','A','B','B'],['A','B']) 

assert list(mismatch(['A','C','A','B','B'],['A','B'])) == [1,4]

function cycle將一直重復該模式,直到它與實際一樣長,然后all將逐個元素檢查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM