I have a list of lists and I am trying to group or cluster them based on their items. A nested list starts a new group if none of the elements are in the previous group.
Input:
paths = [
['D', 'B', 'A', 'H'],
['D', 'B', 'A', 'C'],
['H', 'A', 'C'],
['E', 'G', 'I'],
['F', 'G', 'I']]
My failed Code:
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
Expected Output:
[
[
['D', 'B', 'A', 'H'],
['D', 'B', 'A', 'C'],
['H', 'A', 'C']
],
[
['E', 'G', 'I'],
['F', 'G', 'I']
]
]
Another Example:
paths = [['shifter', 'barrel', 'barrel shifter'],
['ARM', 'barrel', 'barrel shifter'],
['IP power', 'IP', 'power'],
['ARM', 'barrel', 'shifter']]
Expected Output Groups:
output = [
[['shifter', 'barrel', 'barrel shifter'],
['ARM', 'barrel', 'barrel shifter'],
['ARM', 'barrel', 'shifter']],
[['IP power', 'IP', 'power']],
]
See Question&Answers more detail:
os