简体   繁体   English

如果满足条件,则从列表列表中删除列表

[英]Remove list from list of lists if criterion is met

I am looking to program a small bit of code in Python.我希望在 Python 中编写一小段代码。 I have a list of lists called "keep_list", from which I want to remove any sublist containing a specific value found in another list called "deleteNODE".我有一个名为“keep_list”的列表列表,我想从中删除任何包含在另一个名为“deleteNODE”的列表中找到的特定值的子列表。

for example:例如:

deleteNODE=[0,4]
keep_list=[[0,1,2],[0,2,3],[1,2,3],[4,5,6]]

After running the code the result should be (removing any list containing 0 or 4):运行代码后,结果应该是(删除任何包含 0 或 4 的列表):

keep_list=[[1,2,3]]

Is there any efficient way of doing this?有没有有效的方法来做到这一点?

I did it like this:我是这样做的:

[x for x in keep_list if not set(x).intersection(deleteNODE)]

Since I thought the other answers were better, I also ran timeit on all the 3 answers and surprisingly this one was faster.由于我认为其他答案更好,我还对所有 3 个答案运行了 timeit,令人惊讶的是,这个答案更快。

Python 3.8.2
>>> import timeit
>>>
>>> deleteNODE=[0,4]
>>> keep_list=[[0,1,2],[0,2,3],[1,2,3],[4,5,6]]
>>>
>>>
>>> def v1(keep, delete):
...     return [l for l in keep_list if not any(n in l for n in deleteNODE)]
...
>>> def v2(keep, delete):
...     return [i for i in keep_list if len(set(i)&set(deleteNODE)) == 0]
...
>>> def v3(keep, delete):
...     return [x for x in keep_list if not set(x).intersection(deleteNODE)]
...
>>>
>>> timeit.timeit(lambda: v1(keep_list, deleteNODE), number=3000000)
7.2224646
>>> timeit.timeit(lambda: v2(keep_list, deleteNODE), number=3000000)
7.1723587
>>> timeit.timeit(lambda: v3(keep_list, deleteNODE), number=3000000)
5.640403499999998

I'm no Python expert so can anyone understand why mine was faster since it appears to be creating a new set for every evaluation?我不是 Python 专家,所以任何人都可以理解为什么我的速度更快,因为它似乎为每次评估创建了一个新集合?

You can solve this using a list comprehension to cycle through each list within the larger list and by using sets.您可以使用列表推导来循环遍历较大列表中的每个列表并使用集合来解决此问题。 The & operator between sets returns the intersection (the elements common between both sets).集合之间的&运算符返回交集(两个集合之间共有的元素)。 Therefore, if the intersection between the list you're evaluating and deleteNODE is not zero, that means there is a common element and it gets excluded.因此,如果您正在评估的列表和deleteNODE之间的交集不为零,则意味着存在一个公共元素并且它被排除在外。

keep_list = [i for i in keep_list if len(set(i)&set(deleteNODE)) == 0]

This could be done using list comprehension这可以使用列表理解来完成

deleteNODE=[0,4]
keep_list=[[0,1,2],[0,2,3],[1,2,3],[4,5,6]]
...
keep_list = [l for l in keep_list if not any(n in l for n in deleteNODE)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM