Python – 将列表展平为单个元素
有时,在使用Python列表时,我们可能会遇到需要执行列表扁平化的问题,即将混合列表转换为扁平化列表。这可以在使用一维列表作为输入的域中应用。让我们讨论可以执行此任务的某些方式。
方法 #1:使用循环 + isinstance()
上述功能的组合可用于执行此任务。在此,我们检查列表的实例并将其展平以及我们添加到列表中的其余元素。
# Python3 code to demonstrate
# Flatten List to individual elements
# using loop + isinstance()
def flatten(test_list):
if isinstance(test_list, list):
temp = []
for ele in test_list:
temp.extend(flatten(ele))
return temp
else:
return [test_list]
# Initializing list
test_list = ['gfg', 1, [5, 6, 'geeks'], 67.4, [5], 'best']
# printing original list
print("The original list is : " + str(test_list))
# Flatten List to individual elements
# using loop + isinstance()
res = flatten(test_list)
# printing result
print ("The List after flattening : " + str(res))
输出 :
The original list is : [‘gfg’, 1, [5, 6, ‘geeks’], 67.4, [5], ‘best’]
The List after flattening : [‘gfg’, 1, 5, 6, ‘geeks’, 67.4, 5, ‘best’]
方法#2:使用chain() + isinstance()
这是可以执行此任务的另一种方式。在此我们使用 chain() 执行迭代任务,并使用 isinstance() 检查列表实例。
# Python3 code to demonstrate
# Flatten List to individual elements
# using chain() + isinstance()
from itertools import chain
# Initializing list
test_list = ['gfg', 1, [5, 6, 'geeks'], 67.4, [5], 'best']
# printing original list
print("The original list is : " + str(test_list))
# Flatten List to individual elements
# using chain() + isinstance()
res = list(chain(*[ele if isinstance(ele, list) else [ele] for ele in test_list]))
# printing result
print ("The List after flattening : " + str(res))
输出 :
The original list is : [‘gfg’, 1, [5, 6, ‘geeks’], 67.4, [5], ‘best’]
The List after flattening : [‘gfg’, 1, 5, 6, ‘geeks’, 67.4, 5, ‘best’]