📜  Python – 嵌套列表到单值元组

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

Python – 嵌套列表到单值元组

有时,在处理Python数据时,我们可能会遇到需要将Python嵌套列表转换为单值元组的问题。这类问题可以应用在 Web 开发和竞争性编程等领域。让我们讨论可以执行此任务的某些方式。

方法#1:使用列表推导(对于单嵌套)
这是可以执行此任务的方式之一。我们迭代每个内部列表并将每个元素转换为单独的元组。这仅适用于单个嵌套。

# Python3 code to demonstrate working of 
# Convert Nested List to 1 value Tuple
# Using list comprehension
  
# initializing list
test_list = [[5, 6], [4, 7, 10], [12], [9, 11]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Convert Nested List to 1 value Tuple
# Using list comprehension
res = [(ele, ) for sub in test_list for ele in sub]
  
# printing result 
print("The converted container : " + str(res)) 
输出 :
The original list is : [[5, 6], [4, 7, 10], [12], [9, 11]]
The converted container : [(5, ), (6, ), (4, ), (7, ), (10, ), (12, ), (9, ), (11, )]

方法 #2:使用isinstance() + 递归
上述功能的组合可以用来解决这个问题。在此,我们使用 isinstance() 和递归执行展平和转换任务,以适应随机嵌套的情况。

# Python3 code to demonstrate working of 
# Convert Nested List to 1 value Tuple
# Using isinstance() + recursion
  
# helper_fnc
def hlper_fnc(test_list):
    res = []
    if isinstance(test_list, list):
        for ele in test_list:
            res.extend(hlper_fnc(ele))
    elif isinstance(test_list, int):
        res.append((test_list, ))
    return res
  
# initializing list
test_list = [[5, [6]], [4, 7, [10, 45]], [12], [9, 11]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Convert Nested List to 1 value Tuple
# Using isinstance() + recursion
res = hlper_fnc(test_list)
  
# printing result 
print("The converted container : " + str(res)) 
输出 :
The original list is : [[5, [6]], [4, 7, [10, 45]], [12], [9, 11]]
The converted container : [(5, ), (6, ), (4, ), (7, ), (10, ), (45, ), (12, ), (9, ), (11, )]