【发布时间】: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))
对不起,如果代码有点乱。如果有人能指出我正确的方向,将不胜感激。
【问题讨论】: