Reputation: 483
I have a nested list of tuples:
[[(1236.39, -693.34), (1236.8, -697.38), (1236.39, -697.38)],
[(1236.8, -693.34), (1236.39, -693.34), (1236.8, -697.38)],
[(1240.64, -693.15), (1236.6, -693.56), (1236.6, -693.15)],
[(1240.64, -693.56), (1240.64, -693.15), (1236.6, -693.56)],
[(1237.17, -697.82), (1237.19, -697.34), (1237.0, -697.69)],
[(1237.45, -697.53), ([1237.17, -697.82), (1237.19, -697.34)]]
How to group them by two repeating tuples in the lower list:
[[[(1236.39, -693.34), (1236.8, -697.38), (1236.39, -697.38)],
[(1236.8, -693.34), (1236.39, -693.34), (1236.8, -697.38)]],
[[(1240.64, -693.15), (1236.6, -693.56), (1236.6, -693.15)],
[(1240.64, -693.56), (1240.64, -693.15), (1236.6, -693.56)]],
[(1237.17, -697.82), (1237.19, -697.34), (1237.0, -697.69)],
[(1237.45, -697.53), ([1237.17, -697.82), (1237.19, -697.34)]]
i.e. It's like grouping triangles having the common edge. I tried solution from this question, but it returns me wrong result:
[[(1236.8, -693.34), (1236.39, -693.34), (1236.8, -697.38)]]
[[(1240.64, -693.15), (1236.6, -693.56), (1236.6, -693.15)], [(1240.64, -693.56), (1240.64, -693.15), (1236.6, -693.56)]]
[[(1237.17, -697.82), (1237.19, -697.34), (1237.0, -697.69)], [(1237.45, -697.53), (1237.17, -697.82), (1237.19, -697.34)]]
[[(1236.39, -693.34), (1236.8, -697.38), (1236.39, -697.38)]]
It correctly groups lists in the middle, but lists on the edge are not grouped.
Upvotes: 0
Views: 101
Reputation: 1383
Use itertools.groupby
to group the items and a function to check the repeating elements which can be used in groupby
as key
with functools.cmp_to_key
same as mentioned in answers of question you shared.
from itertools import groupby as gby
import functools
def check_common(a, b):
return 0 if any(key in a for key in b) else -1
Result:
>>> key_common = functools.cmp_to_key(check_common)
>>> groups = [list(group) for key, group in gby(input_list, key=key_common)]
>>> groups
>>> [[[(1236.39, -693.34), (1236.8, -697.38), (1236.39, -697.38)],
[(1236.8, -693.34), (1236.39, -693.34), (1236.8, -697.38)]],
[[(1240.64, -693.15), (1236.6, -693.56), (1236.6, -693.15)],
[(1240.64, -693.56), (1240.64, -693.15), (1236.6, -693.56)]],
[[(1237.17, -697.82), (1237.19, -697.34), (1237.0, -697.69)],
[(1237.45, -697.53), (1237.17, -697.82), (1237.19, -697.34)]]
]
Upvotes: 1