使用双递归从列表中删除 John Wick



为了让我接管矩阵,我首先需要从中移除John Wick。他非常善于隐藏(显然(,所以他将自己分成一个列表,并在列表中列出。例如:

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

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

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

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'], []], '')

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

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'], []]

只允许双递归

如果我对此的理解是正确的,那么现有的三个答案并不能解决指定的问题。 它们不是双递归,而是使用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'], []]
def list_purge(lst, rem):
purged = list()
for l in lst:
if isinstance(l, list):
l = list_purge(l, rem)
else:
for c in rem:
l = l.replace(c, '')
if len(l) > 0:
purged.append(l)
return purged

应该给:

>>>>list_purge(["a", ["j", "e", "o"], ["h", "n", "s", "w", "o"], ["i", "c", "k"]], "johnwick")
['a', ['e'], ['s']]

如果你的任务是保留空字符串,那么只需修改代码即可。

最新更新