我有这个递归函数
def recursive_search(x):
y = []
for i in x:
if (i == tuple(i)) or (i == list(i)) or i == set(i):
recursive_search(i)
else:
y.append(i)
print(y)
print(recursive_search(("re",("cur",("sion",(" ",("foo",["bar",{"baz"}])))))))
打印出来
['baz']
['bar']
['foo']
[' ']
['sion']
['cur']
['re']
None
当我将“print(y)”设置为“return y”时,它只打印出“['re']”。如果使用全局y是不安全的,那么我可以采用另一种方式。
答案 0 :(得分:3)
您需要捕获返回值并使用它来构建答案:
def recursive_search(x):
y = []
for i in x:
if type(i) in (tuple, list, set):
y.append(recursive_search(i))
else:
y.append(i)
return y
print(recursive_search(("re",("cur",("sion",(" ",("foo",["bar",{"baz"}])))))))
# ['re', ['cur', ['sion', [' ', ['foo', ['bar', ['baz']]]]]]]
如果您需要嵌套以外的其他东西,您可以使用返回来执行其他操作。
答案 1 :(得分:0)
声明第二个参数,每次调用递归函数时都会这样:
def recursive_search(x,y=None):
if y is None:
y = []
for i in x:
if (i == tuple(i)) or (i == list(i)) or i == set(i):
recursive_search(i, y)
else:
y +=[i]
return y[:]
y = recursive_search(("re",("cur",("sion",(" ",("foo",["bar",{"baz"}]))))))
print(y)
z = recursive_search(("a",("brown",("fox",("jumps ",("over",["foo",{"bar"}]))))))
print(z)
['re', 'cur', 'sion', ' ', 'foo', 'bar', 'baz']
['a', 'brown', 'fox', 'jumps ', 'over', 'foo', 'bar']