Python中子列表的高效匹配

发布于 2024-12-14 11:13:40 字数 474 浏览 3 评论 0原文

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

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

Given a two-dimensional list, I would like to find everything that contains a sublist. I realize I can do something like:

#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

But there seems to be all kinds of bad about this. It seems very unlike the Python code I've seen and dealt with so far, besides I'm making changes to the list while iterating it, which I've read is not at all a good thing. Also, it seems horribly inefficient: while toMatch shouldn't have a length greater then three for my purposes, the length of theList is unknown and could be quite large. Any help is greatly appreciated, and thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

橘香 2024-12-21 11:13:40

我要做的只是保留与“匹配”列表中所有项目匹配的子列表。

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

What I'd do is only keep sub-lists that match all the items in the "match" list.

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

You can speed this up by using a set:

def match_all(the_list, to_match):
    matches = set(to_match).issubset
    return [sublist for sublist in the_list if matches(sublist)]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文