0

I have a csv file where each row contains a pair of values. For example, it might look something like this:

A, B
B, D
E, G
F, G
H, C

Each row should be interpreted to mean that the two values should be in the same group. I'm trying to find an elegant/simple way to take the ordered pairs from the csv and determine the groupings. Based on the pairs above, the groups would be {A, B, D}, {C, H}, {E, F, G} and I would want to output something like:

A, Group 1
B, Group 1
C, Group 2
D, Group 1
E, Group 3
F, Group 3
G, Group 3
H, Group 2

I'm having a hard time wrapping my head around the best way to approach this. Is there a simple way to do this?

Jeff
  • 93
  • 1
  • 11
  • 1
    Does this answer your question? [How to aggregate matching pairs into “connected components” in Python](https://stackoverflow.com/questions/27967093/how-to-aggregate-matching-pairs-into-connected-components-in-python) – Tomerikoo Mar 22 '21 at 14:33
  • That looks really promising! The only thing that isn't immediately obvious to me is in the top answer, how to get from [['a', 'd', 'e', 'b', 'c'], ['f', 'g']] to the format I need of "a, Group 1", etc. – Jeff Mar 22 '21 at 14:40
  • 1
    Maybe something like: `l = [['a', 'd', 'e', 'b', 'c'], ['f', 'g']] ; for i, sub in enumerate(l, 1): for x in sub: print(x, ", Group", i)`? – Tomerikoo Mar 22 '21 at 14:49
  • That worked perfectly!!! Thank you so much. You've made my week :) – Jeff Mar 22 '21 at 15:58
  • 1
    No problem. Happy to do so ^_^ Just, if the link above (together with my comment) actually helped you solve the problem, you should mark the question as a duplicate to the suggested link – Tomerikoo Mar 22 '21 at 16:59

0 Answers0