有个多层列表:[1, 2, 3, 4, [5, 6, [7, 8]], [‘a’, ‘b’, [2, 4]]],拆分成单层列表
顺序不同
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):
for parent_i, parent_ele in enumerate(li):
if isinstance(parent_ele, list):
li.remove(parent_ele)
for sub_i, sub_ele in enumerate(parent_ele):
li.insert(parent_i+sub_i, sub_ele)
li = [1, 2, 3, 4, [5, 6, [7, 8]], ['a', 'b', [2, 4]]]
split(li)
print(li)
# 结果:[1, 2, 3, 4, 5, 6, 7, 8, 'a', 'b', 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]