📜  Python – 扁平化嵌套元组

📅  最后修改于: 2022-05-13 01:54:25.664000             🧑  作者: Mango

Python – 扁平化嵌套元组

有时,在使用Python元组时,我们可能会遇到需要对元组执行扁平化的问题,这可能是嵌套的且不受欢迎的。这可以在许多领域都有应用,例如数据科学和 Web 开发。让我们讨论一下可以执行此任务的特定方式。

Input : test_tuple = ((4, 7), ((4, 5), ((6, 7), (7, 6))))
Output : ((4, 7), (4, 5), (6, 7), (7, 6))

Input : test_tuple = ((4, 7), (5, 7), (1, 3))
Output : ((4, 7), (5, 7), (1, 3))

方法:使用recursion + isinstance()
以上功能的组合可以帮助我们解决这个问题。在这种情况下,我们使用递归来执行挖掘内部元组的每个元组的任务,并且对于扁平化的决定,根据元组容器或原始数据使用 isinstance()。

Python3
# Python3 code to demonstrate working of 
# Flatten Nested Tuples
# Using recursion + isinstance()
  
# helper function
def flatten(test_tuple):
      
    if isinstance(test_tuple, tuple) and len(test_tuple) == 2 and not isinstance(test_tuple[0], tuple):
        res = [test_tuple]
        return tuple(res)
  
    res = []
    for sub in test_tuple:
        res += flatten(sub)
    return tuple(res)
  
# initializing tuple
test_tuple = ((4, 5), ((4, 7), (8, 9), (10, 11)), (((9, 10), (3, 4))))
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# Flatten Nested Tuples
# Using recursion + isinstance()
res = flatten(test_tuple)
  
# printing result 
print("The flattened tuple : " + str(res))


输出 :
The original tuple : ((4, 5), ((4, 7), (8, 9), (10, 11)), ((9, 10), (3, 4)))
The flattened tuple : ((4, 5), (4, 7), (8, 9), (10, 11), (9, 10), (3, 4))