2011-11-09 79 views
2

給定一個二維列表,我想查找包含子列表的所有內容。我知道我可以做類似這樣的事情:Python中子列表的高效匹配

#Psuedo-Python (not kosher) 
def MatchAll(theList,toMatch): 
    result=list(theList) 
    for nMatch in toMatch: 
     for nResult in result: 
      if not nMatch in nResult: 
       result.remove(nResult) 
    return result 

但是這似乎存在各種各樣的問題。它看起來與我迄今爲止看到和處理的Python代碼非常不同,除了在迭代它時對列表進行更改,我讀過的內容並不是一件好事。而且,這似乎是非常低效的:儘管爲了我的目的toMatch的長度不應超過3,但List的長度是未知的,並且可能相當大。任何幫助非常感謝,並提前感謝。

+0

的這種語義是不明確的。 「包含子列表的所有內容」是什麼意思? –

回答

3

我會做的只是保持與「匹配」列表中的所有項目匹配的子列表。

def match_all(the_list, to_match): 
    return [sublist for sublist in the_list 
       if all(item in sublist for item in to_match)] 

您可以通過使用set加快這:

def match_all(the_list, to_match): 
    matches = set(to_match).issubset 
    return [sublist for sublist in the_list if matches(sublist)] 
+0

請設置條件'如果設置(項目)<=設置(to_match)'。 :) –

+0

聖鯉!事後看來,這似乎很明顯。我非常感謝你,先生。 – LHT

+0

呃,你的意思是用set()<= set()位替換所有的位?我猜轉換列表並不是太低效嗎? – LHT