如何展平深度嵌套的元组? [英] How do I Flatten Deeply Nested Tuples?
本文介绍了如何展平深度嵌套的元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我得到一个嵌套的元组结构,每个元组有 2 个元素,我想将其转换为平面结构
I'm given a nested structure of tuples with 2 elements each, and want to convert it to a flat structure
我尝试使用 * 来循环和展平,但由于每个元组都嵌套在另一个元组中而卡住了
I've tried using * to loop through and flatten, but am stuck since each tuple is nested in another one
示例输入:(((((1, 2), 3), 4), 5), 6)
示例输出:(1, 2, 3, 4, 5, 6)
推荐答案
使用递归
def convert(data):
result = []
for item in data:
if isinstance(item, tuple):
result.extend(convert(item))
else:
result.append(item)
return tuple(result)
data = (((((1, 2), 3), 4), 5), 6)
print(convert(data))
这篇关于如何展平深度嵌套的元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文