类似于将列表与公共元素组合起来 https://stackoverflow.com/a/53886179/9698684,解决这个问题的一种方法可能是从嵌套列表中定义一个图,将每个子列表作为一个path https://en.wikipedia.org/wiki/Path_(graph_theory), 和
寻找连接的组件 https://en.wikipedia.org/wiki/Component_(graph_theory):
import networkx as nx
my_list = [[1, 2, 3, 4], [4, 5, 6, 7], [9, 10, 11, 12]]
G=nx.Graph()
for l in my_list:
nx.add_path(G, l)
components = list(nx.connected_components(G))
# [{1, 2, 3, 4, 5, 6, 7}, {9, 10, 11, 12}]
groups = []
for component in components:
group = []
for path in my_list:
if component.issuperset(path):
group.append(path)
groups.append(group)
groups
# [[[1, 2, 3, 4], [4, 5, 6, 7]], [[9, 10, 11, 12]]]