Стек списки во вложенный список, как матрешка в Python - PullRequest
0 голосов
/ 19 октября 2018

У меня есть несколько «больших» списков, которые вписываются в некоторые другие списки из того же списка «больших» списков, и я хотел бы сопоставить подсписки друг с другом, чтобы получить один, содержащий все остальные.Сначала сортируется по длине элементов.

lists =  [['Linden'], ['Linden', 'N.J.'], ['chemical', 'plants'], ['some', 'federal', 'officials'], ['the', 'other', 'side', 'of', 'the', 'country'], ['the', 'most', 'dangerous', 'two', 'miles', 'in', 'America'], ['that', 'some', 'federal', 'officials', 'refer', 'to', 'as', 'the', 'most', 'dangerous', 'two', 'miles', 'in', 'America'], ['an', 'industrial', 'corridor', 'of', 'chemical', 'plants', 'that', 'some', 'federal', 'officials', 'refer', 'to', 'as', 'the', 'most', 'dangerous', 'two', 'miles', 'in', 'America'], ['At', 'the', 'other', 'side', 'of', 'the', 'country', 'Linden', 'N.J.', 'is', 'part', 'of', 'an', 'industrial', 'corridor', 'of', 'chemical', 'plants', 'and', 'oil', 'refineries', 'that', 'some', 'federal', 'officials', 'refer', 'to', 'as', 'the', 'most', 'dangerous', 'two', 'miles', 'in', 'America']]

, и результат должен быть:

['At', ['the', 'other', 'side', 'of', 'the', 'country'], [['Linden'], 'N.J.'], 'is', 'part', 'of', ['an', 'industrial', 'corridor', 'of', ['chemical', 'plants'], 'and', 'oil', 'refineries', 'that', ['some', 'federal', 'officials'], 'refer', 'to', 'as', ['the', 'most', 'dangerous', 'two', 'miles', 'in', 'America']]]

Как это решить?

1 Ответ

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

Я нашел свое собственное решение после некоторых запрещенных попыток задать это в stackoverflow.Итак, вот оно:

Если у вас есть идеи по оптимизации, я был бы рад этому.Я хотел бы использовать какой-то итератор вместо рекурсивной функции, как здесь ( итерация вложенных списков Python эффективно ), но в этом испытании, которое у меня было, оно выровняло вложение списка.

from more_itertools import replace
import collections

nestlist =  [['Linden'],['Linden', 'N.J.'], ['chemical', 'plants'], ['some', 'federal', 'officials'], ['the', 'other', 'side', 'of', 'the', 'country'], ['the', 'most', 'dangerous', 'two', 'miles', 'in', 'America'], ['that', 'some', 'federal', 'officials', 'refer', 'to', 'as', 'the', 'most', 'dangerous', 'two', 'miles', 'in', 'America'], ['an', 'industrial', 'corridor', 'of', 'chemical', 'plants', 'that', 'some', 'federal', 'officials', 'refer', 'to', 'as', 'the', 'most', 'dangerous', 'two', 'miles', 'in', 'America'], ['At', 'the', 'other', 'side', 'of', 'the', 'country', 'Linden', 'N.J.', 'is', 'part', 'of', 'an', 'industrial', 'corridor', 'of', 'chemical', 'plants', 'and', 'oil', 'refineries', 'that', 'some', 'federal', 'officials', 'refer', 'to', 'as', 'the', 'most', 'dangerous', 'two', 'miles', 'in', 'America']]

#nestlist =  [['Linden', 'N.J.'], ['chemical', 'plants'], ['country', 'Linden', 'N.J.', 'of', 'chemical', 'plants']]

#nestlist =  [['Linden', 'N.J.'], ['Linden', 'N.J.', 'of'], ['country', 'Linden', 'N.J.', 'of', 'chemical', 'plants']]


def flatten(iterable):
    for el in iterable:
        if isinstance(el, collections.Iterable) and not isinstance(el, str):
            yield from flatten(el)
        else:
            yield el

def on_each_iterable (lol, fun):
    out = []
    if isinstance(lol, collections.Iterable) and not isinstance(lol, str):
        for x in lol:
            out.append(on_each_iterable(x, fun))
        out = fun(out)
    else:
        out = lol
    return out


def stack_matrjoshka(nesting_list):
    nesting_list = sorted(nesting_list, key=lambda x: len(x))
    n = 0
    while n < (len(nesting_list) - 2):
        to_fit_there = nesting_list[n]
        flatted_to_fit_there = list(flatten(to_fit_there[:]))

        def is_fitting(*xs):
            flatted_compared = list(flatten(xs[:]))
            decision = flatted_compared == list(flatted_to_fit_there)
            return decision

        for m in range(n + 1, len(nesting_list)):
            through = list(nesting_list[m])

            def replacing_fun(x):
                return list(replace(list(x), is_fitting, [to_fit_there], window_size=len(to_fit_there)))

            nesting_list[m] = on_each_iterable(through, replacing_fun)

        n = n + 1
    return (nesting_list[-1])


nested_list = stack_matrjoshka(nestlist)
print (nested_list)

делает

['At', ['the', 'other', 'side', 'of', 'the', 'country'], [['Linden'], 'N.J.'], 'is', 'part', 'of', 'an', 'industrial', 'corridor', 'of', ['chemical', 'plants'], 'and', 'oil', 'refineries', ['that', ['some', 'federal', 'officials'], 'refer', 'to', 'as', ['the', 'most', 'dangerous', 'two', 'miles', 'in', 'America']]]
...