将嵌套列表展平为元组列表的Python程序
给定一个元组列表,每个元组环绕多个列表,我们的任务是编写一个Python程序将容器扁平化为一个元组列表。
Input : test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]
Output : [(4, 6), (7, 4), (10, 3)]
Explanation : The surrounded lists are omitted around each tuple.
Input : test_list = [[[(4, 6)]], [[[(7, 4)]]]]
Output : [(4, 6), (7, 4)]
Explanation : The surrounded lists are omitted around each tuple.
方法 #1:使用递归+ isinstance()
在此,使用 isinstance() 测试容器包装是否为列表。递归策略用于检查列表是否重复展平直到元组。
Python3
# Python3 code to demonstrate working of
# Multiflatten Tuple List
# Using recursion + isinstance()
res = []
def remove_lists(test_list):
for ele in test_list:
# checking for wrapped list
if isinstance(ele, list):
remove_lists(ele)
else:
res.append(ele)
return res
# initializing list
test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]
# printing original list
print("The original list is : " + str(test_list))
# calling recursive function
res = remove_lists(test_list)
# printing result
print("The Flattened container : " + str(res))
Python3
# Python3 code to demonstrate working of
# Multiflatten Tuple List
# Using yield + recursion
def remove_lists(test_list):
if isinstance(test_list, list):
# return intermediate to recursive function
for ele in test_list:
yield from remove_lists(ele)
else:
yield test_list
# initializing list
test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]
# printing original list
print("The original list is : " + str(test_list))
# calling recursive function
res = list(remove_lists(test_list))
# printing result
print("The Flattened container : " + str(res))
输出:
The original list is : [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]
The Flattened container : [(4, 6), (7, 4), (10, 3)]
方法#2:使用yield + recursion
此方法使用递归执行类似的任务。生成器用于使用 yield 关键字处理中间结果。
蟒蛇3
# Python3 code to demonstrate working of
# Multiflatten Tuple List
# Using yield + recursion
def remove_lists(test_list):
if isinstance(test_list, list):
# return intermediate to recursive function
for ele in test_list:
yield from remove_lists(ele)
else:
yield test_list
# initializing list
test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]
# printing original list
print("The original list is : " + str(test_list))
# calling recursive function
res = list(remove_lists(test_list))
# printing result
print("The Flattened container : " + str(res))
输出:
The original list is : [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]
The Flattened container : [(4, 6), (7, 4), (10, 3)]