您能展平这样的元组吗?
(42, (23, (22, (17, []))))
成为所有元素的一个元组:
(42,23,22,17)
?
答案 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)