[英]Python remove sublist in a list if specific element inside this sublist
For example 例如
list_of_specific_element = [2,13]
list = [[1, 0], [2, 1], [2, 3], [13, 12], [13, 14], [15, 13]]
I want the sublist including any value inside the list of specific element be removed from the list. 我希望从列表中删除子列表,包括特定元素列表中的任何值。
So the element [2,1],[2,3],[13,12],[13,14]
should be removed from the list. 因此
[2,1],[2,3],[13,12],[13,14]
应从列表中删除元素[2,1],[2,3],[13,12],[13,14]
。
the final output list should be [[1,0],[15,13]]
最终的输出列表应为
[[1,0],[15,13]]
listy=[elem for elem in listy if (elem[0] not in list_of_specific_element) and (elem[1] not in list_of_specific_element)]
使用列表理解单行
You could use set intersections: 你可以使用set intersection:
>>> 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]]
You could write: 你可以写:
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))
]
which gives: 这使:
>>> output
[[1, 0]]
This uses sets, set intersection and list comprehension. 这使用集合,集合交集和列表理解。
A simple list-only solution: 一个简单的列表解决方案:
list = [x for x in list if all(e not in list_of_specific_element for e in x)]
And you really shouldn't call it list
! 你真的不应该把它
list
!
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]]
You can use list comprehension
and any()
to do the trick like this example: 你可以使用
list comprehension
和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)
Output: 输出:
[[1, 0]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.