📜  Python – 将 List 的元组展平为元组

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

Python – 将 List 的元组展平为元组

有时,在使用Python元组时,我们可能会遇到需要执行元组扁平化的问题,元组以列表作为其组成元素。这种问题在机器学习等数据领域中很常见。让我们讨论可以执行此任务的某些方式。

方法#1:使用sum() + tuple()
上述功能的组合可以用来解决这个问题。在此,我们使用 sum() 执行展平任务,将空列表作为参数传递。

# Python3 code to demonstrate working of 
# Flatten tuple of List to tuple
# Using sum() + tuple()
  
# initializing tuple
test_tuple = ([5, 6], [6, 7, 8, 9], [3])
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# Flatten tuple of List to tuple
# Using sum() + tuple()
res = tuple(sum(test_tuple, []))
  
# printing result 
print("The flattened tuple : " + str(res))
输出 :
The original tuple : ([5, 6], [6, 7, 8, 9], [3])
The flattened tuple : (5, 6, 6, 7, 8, 9, 3)

方法 #2:使用tuple() + chain.from_iterable()
上述功能的组合可以用来解决这个问题。在此,我们使用 from_iterable() 执行展平任务,并使用 tuple() 执行转换为元组的任务。

# Python3 code to demonstrate working of 
# Flatten tuple of List to tuple
# Using tuple() + chain.from_iterable()
from itertools import chain
  
# initializing tuple
test_tuple = ([5, 6], [6, 7, 8, 9], [3])
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# Flatten tuple of List to tuple
# Using tuple() + chain.from_iterable()
res = tuple(chain.from_iterable(test_tuple))
  
# printing result 
print("The flattened tuple : " + str(res))
输出 :
The original tuple : ([5, 6], [6, 7, 8, 9], [3])
The flattened tuple : (5, 6, 6, 7, 8, 9, 3)