【问题标题】:Grouping sublists based on common demoninator [duplicate]根据共同的恶魔对子列表进行分组[重复]
【发布时间】:2019-10-23 11:26:22
【问题描述】:

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

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))

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

【问题讨论】:

    标签: python list


    【解决方案1】:

    您正在寻找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}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-03
      • 1970-01-01
      • 2015-05-01
      • 1970-01-01
      • 2019-11-20
      • 1970-01-01
      • 2023-02-07
      相关资源
      最近更新 更多