我有一个嵌套列表:
regions = [[1,2,3],[3,4],[1,3,4],[1,2,3,5]]
我想删除此嵌套列表中包含在另一个列表中的每个列表,即[1,3,4]中包含的[3,4]和[1,2,3中包含的[1,2,3] ,3,5],因此结果为:
result = [[1,3,4],[1,2,3,5]]
到目前为止,我正在做
regions_remove = []
for i,reg_i in enumerate(regions):
for j,reg_j in enumerate(regions):
if j != i and list(set(reg_i)-set(reg_j)) == []:
regions_remove.append(reg_i)
regions = [list(item) for item in set(tuple(row) for row in regions) -
set(tuple(row) for row in regions_remove)]
我得到了:regions = [[1, 2, 3, 5], [1, 3, 4]]
,这是一个解决方案,但是我想知道什么是最有效的pythonic解决方案?
(很抱歉以前没有发布我的完整代码,对此我是新手。
答案 0 :(得分:0)
我绝对忽略了一条更简单的路线,但是这种方法有效
列表理解
from itertools import product
l = [[1,2,3],[3,4],[1,3,4],[1,2,3,5]]
bad = [i for i in l for j in l if i != j if tuple(i) in product(j, repeat = len(i))]
final = [i for i in l if i not in bad]
详细说明
from itertools import product
l = [[1,2,3],[3,4],[1,3,4],[1,2,3,5]]
bad = []
for i in l:
for j in l:
if i != j:
if tuple(i) in product(j, repeat = len(i)):
bad.append(i)
final = [i for i in l if i not in bad]
print(final)
[[1, 3, 4], [1, 2, 3, 5]]
答案 1 :(得分:0)
这是一个具有列表理解和sudo npm install <package>
函数的解决方案:
all()
返回:
nested_list = [[1,2,3],[3,4],[1,3,4],[1,2,3,5],[2,5]]
result = list(nested_list) #makes a copy of the initial list
for l1 in nested_list: #list in nested_list
rest = list(result) #makes a copy of the current result list
rest.remove(l1) #the list l1 will be compared to every other list (so except itself)
for l2 in rest: #list to compare
if all([elt in l2 for elt in l1]): result.remove(l1)
#if all the elements of l1 are in l2 (then all() gives True), it is removed
更多帮助
all()内置函数:https://docs.python.org/2/library/functions.html#all
复制列表:https://docs.python.org/2/library/functions.html#func-list
列表理解:https://www.pythonforbeginners.com/basics/list-comprehensions-in-python