使用内置方法

结果和原列表顺序不同

def split(li):
pop_index_list = [] # 用来存储需要删除元素的索引
for ele in li:
if isinstance(ele, list):
pop_index_list.insert(0, li.index(ele))
li.extend(ele) for i in pop_index_list:
li.pop(i) li = [1, 2, 3, 4, [5, 6, [7, 8]], ['a', 'b', [2, 4]]]
split(li)
print(li)
# 结果 [1, 2, 3, 4, 5, 6, 'a', 'b', 7, 8, 2, 4]

递归方式

def split(li:list, new_list=[]):
for ele in li:
if isinstance(ele, list):
split(ele)
else:
new_list.append(ele)
return new_list
li = [1, 2, 3, 4, [5, 6, [7, 8]], ['a', 'b', [2, 4]]]
print(split(li))
# 结果:[1, 2, 3, 4, 5, 6, 7, 8, 'a', 'b', 2, 4]
05-22 04:28