Python中如果子列表中包含特定元素,则删除列表中的子列表

4
例如。
list_of_specific_element = [2,13]
list = [[1, 0], [2, 1], [2, 3], [13, 12], [13, 14], [15, 13]]

我希望将包含在特定元素列表中的任何值的子列表从列表中移除。
因此,应该从列表中删除元素[2,1]、[2,3]、[13,12]、[13,14]
最终输出的列表应为[[1,0],[15,13]]

5
为什么[15, 13]还会保留?它确实包含一个13 - MSeifert
7个回答

4
listy=[elem for elem in listy if (elem[0] not in list_of_specific_element) and (elem[1] not in list_of_specific_element)]

使用列表推导式一行代码

1
不要使用“list”作为变量名,因为它是一个内置函数的名称。 - Sam Redway
这是提问者使用的变量名称。 - whackamadoodle3000
1
@whackamadoodle3000 这并不意味着你必须重复同样的“错误”。 - Pedro Lobito
1
改成了列表 - whackamadoodle3000

2
您可以使用集合交集:
>>> exclude = {2, 13}
>>> lst = [[1, 0], [2, 1], [2, 3], [13, 12], [13, 14], [15, 13]]
>>> [sublist for sublist in lst if not exclude.intersection(sublist)]
[[1, 0]]

1
您可以写成:

您可以这样书写:

list_of_specific_element = [2,13]
set_of_specific_element = set(list_of_specific_element)
mylist = [[1, 0], [2, 1], [2, 3], [13, 12], [13, 14], [15, 13]]
output = [
    item
    for item in mylist
    if not set_of_specific_element.intersection(set(item))
]

它的意思是:

>>> output
[[1, 0]]

这里使用了集合、集合交集和列表推导。

1
一个简单的仅限列表的解决方案:
list = [x for x in list if all(e not in list_of_specific_element for e in x)]

你真的不应该把它称为list


1

过滤器和lambda版本

list_of_specific_element = [2,13]
list = [[1, 0], [2, 1], [2, 3], [13, 12], [13, 14], [15, 13]]

filtered = filter(lambda item: item[0] not in list_of_specific_element, list)

print(filtered)

>>> [[1, 0], [15, 13]]

1
你可以使用列表推导式any()方法来实现这个例子中的技巧:
list_of_specific_element = [2,13]
# PS: Avoid calling your list a 'list' variable
# You can call it somthing else.
my_list = [[1, 0], [2, 1], [2, 3], [13, 12], [13, 14], [15, 13]]
final = [k for k in my_list if not any(j in list_of_specific_element for j in k)]
print(final)

输出:

[[1, 0]]

1

我猜你可以使用:

match = [2,13]
lst = [[1, 0], [2, 1], [2, 3], [13, 12], [13, 14], [15, 13]]

[[lst.remove(subl) for m in match if m in subl]for subl in lst[:]]

演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接