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 的长度对于我的目的来说不应该大于三,但 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我要做的只是保留与“匹配”列表中所有项目匹配的子列表。
您可以使用
set
来加快速度:What I'd do is only keep sub-lists that match all the items in the "match" list.
You can speed this up by using a
set
: