list1 = [2, 1, 3, 4, 5, 7, 9, 8, 12, 13, 14, 15]
# 递归,寻找符合条件的所有元素元素
def get_li(list1, l, con_list):
w1_list = list1.copy()
w2 = list1.copy()
for i in con_list:
w2.remove(i)
if len(w2) == 0:
return con_list
for wl in w2:
if abs(l - wl) == 1:
con_list.append(wl)
return get_li(w1_list, wl, con_list)
return con_list
# 得到最终的链列表
def connect_l(list1):
existlist = []
ds_list = []
for l in list1:
if l not in existlist:
ws = get_li(list1, l, [l])
ds_list.append(ws)
for e in ws:
existlist.append(e)
return ds_list
li = connect_l(list1)
# 删除小列表,如:[3,2,1]包含[1,2],删除[1,2]得到最优列表组合
ret_li = li.copy()
for i in range(len(li) - 1):
if [c for c in li[i] if c in li[i + 1]]:
if li[i] in ret_li:
ret_li.remove(li[i])
print(ret_li)