任务是在Python中将嵌套列表转换为单个列表,即,无论Python列表中有多少层嵌套,都必须删除所有嵌套,才能将其转换为包含所有在最外面的方括号内列出,但内部没有任何方括号。
例子:
Input : l = [1, 2, [3, 4, [5, 6] ], 7, 8, [9, [10] ] ]
Output : l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Input : l = [[[‘item1’, ‘item2’]], [[‘item3’, ‘item4’]]]
Output : l = [‘item1’, ‘item2’, ‘itm3, ‘item4”]
我们使用递归是因为嵌套级别无法预先确定。
# Python code to flat a nested list with
# multiple levels of nesting allowed.
# input list
l = [1, 2, [3, 4, [5, 6]], 7, 8, [9, [10]]]
# output list
output = []
# function used for removing nested
# lists in python.
def reemovNestings(l):
for i in l:
if type(i) == list:
reemovNestings(i)
else:
output.append(i)
# Driver code
print ('The original list: ', l)
reemovNestings(l)
print ('The list after removing nesting: ', output)
输出:
The original list: [1, 2, [3, 4, [5, 6]], 7, 8, [9, [10]]]
The list after removing nesting: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]