簡體   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