我正在使用他的代码来展平嵌套元组:
def get_tuple_leaves(t, out=[]):
for i in t:
if isinstance(i, str):
yield i
else:
get_tuple_leaves(i, out)
我们的想法是获得一个输入,例如((' a',' b'),' c')转向(' a',' b',' c')
但由于某种原因,递归调用永远不会被执行,输出是(' c')
答案 0 :(得分:2)
你没有回来,或者更确切地说,从你的递归电话中屈服。尝试:
def get_tuple_leaves(t, out=[]):
for i in t:
if isinstance(i, str):
yield i
else:
yield from get_tuple_leaves(i, out)
print(list(get_tuple_leaves((('a', 'b'), 'c'))))
导致:
['a', 'b', 'c']