嵌套元组的展平

Pet*_*efi 1 python tuples flatten

你能展平这样的元组吗:

(42, (23, (22, (17, []))))
Run Code Online (Sandbox Code Playgroud)

成为所有元素的一个元组:

(42,23,22,17)
Run Code Online (Sandbox Code Playgroud)

?

And*_*ely 5

使用递归的解决方案:

tpl = (42, (23, (22, (17, []))))

def flatten(tpl):
    if isinstance(tpl, (tuple, list)):
        for v in tpl:
            yield from flatten(v)
    else:
        yield tpl

print(tuple(flatten(tpl)))
Run Code Online (Sandbox Code Playgroud)

印刷:

(42, 23, 22, 17)
Run Code Online (Sandbox Code Playgroud)