繁体   English   中英

如果列表包含在同一嵌套列表Python的另一个列表中,则将其删除

[英]Remove list if it's contained in another list within the same nested list Python

我有一个嵌套列表:

regions = [[1,2,3],[3,4],[1,3,4],[1,2,3,5]]

我想删除此嵌套列表中包含在另一个列表中的每个列表,即[1,3,4]中包含的[3,4]和[1,2,3中包含的[1,2,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解决方案?

(很抱歉,您之前没有发布完整的代码,对此我是新手。

我绝对忽略了一条更简单的路线,但是这种方法有效

清单理解

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

这是一个具有列表理解和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

收益:

[[1, 3, 4], [1, 2, 3, 5]]

进一步的帮助

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM