[英]Python remove sublist in a list if specific element inside this sublist
例如
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]
應從列表中刪除元素[2,1],[2,3],[13,12],[13,14]
。
最終的輸出列表應為[[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)]
使用列表理解單行
你可以使用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]]
你可以寫:
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]]
這使用集合,集合交集和列表理解。
一個簡單的列表解決方案:
list = [x for x in list if all(e not in list_of_specific_element for e in x)]
你真的不應該把它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]]
你可以使用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)
輸出:
[[1, 0]]
我猜你可以用:
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[:]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.