python 合并列表中有相同元素的列表
输入列表: [[1,2,3], [2,1], [3,4], [5], [6,7]] ,把其中有相同值的列表进行合并
输出列表:[[1, 2, 3, 4], [5], [6, 7]]
代码:
def found_idx(lst, k):
"""
lst: [[1,2,3], [2,1], [3,4], [5], [6,7]]
k = 3
return: [0,2], [1,2,3,4] # idx, which '3' in [1,2,3], [3,4]
"""
idx = []
for i,js in enumerate(lst):
for j in js:
if j == k:
idx.append(i)
continue
mg_lst = []
for x in idx:
mg_lst += lst[x]
return idx, list(set(mg_lst))
def merge_lst(lst):
"""
lst: [[1,2,3], [2,1], [3,4], [5], [6,7]]
return: [[1,2,3,4], [5], [6,7]]
"""
outlst = []
for i, js in enumerate(lst):
for j in js:
idx, mg_lst = found_idx(lst, j)
if mg_lst not in outlst:
outlst.append(list(mg_lst))
if outlst == lst:
return outlst
else:
return merge_lst(outlst)
merge_lst([[1,2,3], [2,1], [3,4], [5], [6,7]])
# [[1, 2, 3, 4], [5], [6, 7]]