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

时间:2017-05-27 21:36:55

标签: python list

例如

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

7 个答案:

答案 0 :(得分:3)

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

使用list comprehension one-liner

答案 1 :(得分: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]]

答案 2 :(得分: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]]

这使用集合,设置交集和列表理解。

答案 3 :(得分:1)

一个简单的仅限列表的解决方案:

list = [x for x in list if all(e not in list_of_specific_element for e in x)]

你真的不应该叫它list

答案 4 :(得分: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]]

答案 5 :(得分:1)

您可以使用list comprehensionany()来执行此示例:

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

答案 6 :(得分: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[:]]

demo