我有一个列表列表,我试图根据它们的项目对它们进行分组或聚类。如果上一个组中没有元素,则嵌套列表将开始一个新组。
输入:
paths = [
['D', 'B', 'A', 'H'],
['D', 'B', 'A', 'C'],
['H', 'A', 'C'],
['E', 'G', 'I'],
['F', 'G', 'I']]
我失败的代码:
paths = [
['D', 'B', 'A', 'H'],
['D', 'B', 'A', 'C'],
['H', 'A', 'C'],
['E', 'G', 'I'],
['F', 'G', 'I']
]
groups = []
paths_clone = paths
for path in paths:
for node in path:
for path_clone in paths_clone:
if node in path_clone:
if not path == path_clone:
groups.append([path, path_clone])
else:
groups.append(path)
print groups
预期产量:
[
[
['D', 'B', 'A', 'H'],
['D', 'B', 'A', 'C'],
['H', 'A', 'C']
],
[
['E', 'G', 'I'],
['F', 'G', 'I']
]
]
另一个例子:
paths = [['shifter', 'barrel', 'barrel shifter'],
['ARM', 'barrel', 'barrel shifter'],
['IP power', 'IP', 'power'],
['ARM', 'barrel', 'shifter']]
预期的输出组:
output = [
[['shifter', 'barrel', 'barrel shifter'],
['ARM', 'barrel', 'barrel shifter'],
['ARM', 'barrel', 'shifter']],
[['IP power', 'IP', 'power']],
]