简体   繁体   中英

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

I have a nested list:

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

I want to remove every list in this nested list which is contained in another one, ie, [3,4] contained in [1,3,4] and [1,2,3] contained in [1,2,3,5], so the result is:

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

So far I'm doing:

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

And I've got: regions = [[1, 2, 3, 5], [1, 3, 4]] and this is a solution, but I'd like to know what's the most pythonic solution?

(sorry for not posting my entire code before, I'm a new to this...

I'm definitely overlooking a simpler route, but this approach works

list comprehension

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]

Expanded explanation

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

Here is a solution with list comprehension and all() function :

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

returns:

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

Further help

all() built-in function: https://docs.python.org/2/library/functions.html#all

copy a list: https://docs.python.org/2/library/functions.html#func-list

list comprehension: https://www.pythonforbeginners.com/basics/list-comprehensions-in-python

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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