2

给定一个二维列表,我想找到包含子列表的所有内容。我意识到我可以做类似的事情:

#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 的长度是未知的并且可能非常大。非常感谢任何帮助,并在此先感谢。

4

1 回答 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)]
于 2011-11-09T22:48:05.363 回答