嵌套元组的扁平化

Flattening of nested tuples

你能把这样的元组展平吗:

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

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

(42,23,22,17)

?

使用递归的解决方案:

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

打印:

(42, 23, 22, 17)