使用双重递归从列表中删除johnwick

2024-09-26 17:55:04 发布

您现在位置:Python中文网/ 问答频道 /正文

为了让我接管黑客帝国,我首先需要把约翰·威克从里面除掉。他很擅长隐藏(很明显),所以他把自己分成了一个列表和列表中的列表。例如:

environment = ["a", [**"j"**, "e", **"o"**], [**"h"**, **"n"**, "s", 
    **"w"**, "o"], [**"i", "c", "k"**]]

target = "johnwick"

只有双递归才能将John Wick从矩阵的列表中删除。他不属于这里。到目前为止,我得出的结论是:

def no_wick(environment):
    target = "johnwick"
    clean_matrix = []
    if not environment:
        return clean_matrix
    elif isinstance(environment[0], list): 

        ???????

    elif environment[0] not in target:
        return clean_matrix.append(environment[0]) + no_wick(environment[1:])
    else: 
        return no_wick(environment[1:])

你能帮我把约翰·威克从黑客帝国除掉吗,而我要照顾托马斯·A·安德森?你知道吗


Tags: nocleantarget列表returnenvironmentnot矩阵
3条回答

递归,带有一点可变参数的黑魔法:

def purge(env, target, pos=None):
    if pos is None:
        pos = [0]

    for x in env:
        if pos[0] >= len(target):
            yield x
        if isinstance(x, list):
            x = list(purge(x, target, pos=pos))
            yield x
        elif x != target[pos[0]]:
            yield x
        else:
            pos[0] += 1

env = ["a", ["j", "e", "o"], ["h", "n", "s", "w", "o"], ["i", "c", "k"]]
print(list(purge(env, "johnwick")))

提供:

['a', ['e'], ['s', 'o'], []]

如果我理解正确,这个例子可以帮助您:

In [1]: target = 'johnwick'

In [2]: environment = ['a', ['j', 'e', 'o'], ['h', 'n', 's', 'w', 'o'], ['i', 'c', 'k']]

In [3]: def no_wick(l, target):
   ...:     clear = []
   ...:     for x in l:
   ...:         if isinstance(x, list):
   ...:             x, target = no_wick(x, target)
   ...:             clear.append(x)
   ...:         else:
   ...:             if target.startswith(x):
   ...:                 target = target[1:]
   ...:             else:
   ...:                 clear.append(x)
   ...:     return clear, target


In [4]: no_wick(environment, target)
Out[4]: (['a', ['e'], ['s', 'o'], []], '')

Only double recursion is allowed

如果我对这一点的理解是正确的,那么现有的三个答案并不能按规定解决问题。它们不使用双递归,而是使用for循环来替换其中一个递归。我猜你在找什么:

environment = ["a", ["j", "e", "o"], ["h", "n", "s", "w", "o"], ["i", "c", "k"]]

target = "johnwick"

def no_wick(structure, string, letters=None):

    if letters is None:
        letters = list(string)

    if not letters or not structure:
        return structure

    head, *tail = structure

    if isinstance(head, str):
        if head == letters[0]:
            letters.pop(0)
            head = []
        else:
            head = [head]

        return head + no_wick(tail, string, letters)

    return [no_wick(head, string, letters)] + no_wick(tail, string, letters)  # the double recursion

print(no_wick(environment, target))

输出

['a', ['e'], ['s', 'o'], []]

相关问题 更多 >

    热门问题