在Python中高效匹配子列表

3 投票
1 回答
2392 浏览
提问于 2025-04-17 06:00

给定一个二维列表,我想找到所有包含子列表的元素。我意识到我可以这样做:

#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的长度不应该超过三,但theList的长度是未知的,可能会非常大。非常感谢任何帮助,提前谢谢大家。

1 个回答

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)]

撰写回答