嵌套元组的展平

时间:2020-06-14 21:52:08

标签: python tuples flatten

您能展平这样的元组吗?

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

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

(42,23,22,17)

1 个答案:

答案 0 :(得分: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)))

打印:

(42, 23, 22, 17)