Удалить список, если он содержится в другом списке в том же вложенном списке Python - PullRequest
0 голосов
/ 02 октября 2018

У меня есть вложенный список:

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

Я хочу удалить каждый список в этом вложенном списке, который содержится в другом, т. Е. [3,4] содержится в [1,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]], и это решение, но я хотел бы знать, какое решение является наиболее питоническим?

(извините, что не выкладывал весь свой код раньше, я новичокк этому ...

Ответы [ 2 ]

0 голосов
/ 03 октября 2018

Вот решение с пониманием списка и функцией 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

0 голосов
/ 02 октября 2018

Я определенно пропускаю более простой маршрут, но этот подход работает

понимание списка

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]]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...