Python 基于公共demoninator的分组子列表
我有一个未排序的子列表,如下所示:Python 基于公共demoninator的分组子列表,python,list,Python,List,我有一个未排序的子列表,如下所示: listToGroup = [[123, 134], [134, 153], [134, 158], [123], [537, 190], [190], [537, 950], [950, 650]] sortedList = [[123, 134, 153, 158], [190, 537, 950, 650]] 我要做的是根据子列表之间的连接对子列表进行分组。起始值始终是包含单个项的子列表,即示例中的[123]或[190]。结果应该如下所示: list
listToGroup = [[123, 134], [134, 153], [134, 158], [123], [537, 190], [190], [537, 950], [950, 650]]
sortedList = [[123, 134, 153, 158], [190, 537, 950, 650]]
我要做的是根据子列表之间的连接对子列表进行分组。起始值始终是包含单个项的子列表,即示例中的[123]或[190]。结果应该如下所示:
listToGroup = [[123, 134], [134, 153], [134, 158], [123], [537, 190], [190], [537, 950], [950, 650]]
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))
对不起,如果代码有点乱。如果有人能为我指出正确的方向,我将不胜感激。您正在寻找
连接的组件。您可以按“回答”中的方式继续,但会筛选出单个项目子列表,因为它们不会添加任何连接,并且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}]