我有一个未排序的子列表,如下所示:
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))
对不起,如果代码有点乱。如果有人能为我指出正确的方向,我将不胜感激
您正在寻找
connected components
。您可以在this应答中继续,但筛选出单个项子列表,因为它们不会添加任何连接,并且networkX
会引发错误:相关问题 更多 >
编程相关推荐