基于公共demonin的分组子列表

2024-09-28 10:12:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个未排序的子列表,如下所示:

listToGroup = [[123, 134], [134, 153], [134, 158], [123], [537, 190], [190], [537, 950], [950, 650]]

我要做的是根据子列表之间的连接对子列表进行分组。起始值始终是包含单个项的子列表,即示例中的[123]或[190]。结果应该如下所示:

sortedList = [[123, 134, 153, 158], [190, 537, 950, 650]]

我的数据集由大约1000个这样的子列表组成。 我曾想过如下图所示递归地解决这个问题,但我认为我已经走到了这一步

def listGrouper(startItem, listToGroup):
    groupedList = []
    checkedIndexes = []
    groupedList.append(startItem)

    for index, subList in enumerate(listToGroup):
        if len(subList) > 1:
            if startItem in subList and index not in checkedIndexes:
                if subList.index(startItem) == 0:
                    nextItem = subList[1]
                elif subList.index(startItem) == 1:
                    nextItem = subList[0]

                checkedIndexes.append(index)
                groupedList.append(listGrouper(nextItem, listToGroup))

     return [item for item in groupedList]

 sortedList = []

 for subList in listToGroup:
     if len(subList) == 1:
         sortedList.append(listGrouper(subList[0], listToGroup))

对不起,如果代码有点乱。如果有人能为我指出正确的方向,我将不胜感激


Tags: in列表forindexlenifappendsortedlist
1条回答
网友
1楼 · 发布于 2024-09-28 10:12:24

您正在寻找connected components。您可以在this应答中继续,但筛选出单个项子列表,因为它们不会添加任何连接,并且networkX会引发错误:

import networkx as nx
G=nx.Graph()
G.add_edges_from(i for i in listToGroup if len(i)==2)

list(nx.connected_components(G))
# [{123, 134, 153, 158}, {190, 537, 650, 950}]

相关问题 更多 >

    热门问题