我有一个列表列表,我正在尝试根据它们的项目对它们进行分组或聚类。如果没有元素在前一个组中,则嵌套列表会启动一个新组。
输入:
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']],
]