I want to find two sublists in a list by an element they contain, and then union them, keeping them in the list.
I have this code that seems to do the job, but it seems rather clunky. Is there a better way to do it?
It finds the sublists from the example list 'groups' containing b and g, then unions them. You have to do the check to verify that the elements don't belong to the same sub-list already, or else you end up deleting the sub-list they're both contained in.
The master list will always be two levels deep, and wouldn't have any duplicates.
groups = {{a}, {b, c}, {d}, {e, f, g}}
firstPart = b;
secondPart = g;
fPAddress = Part[Position[groups, firstPart, 2], 1, 1];
sPAddress = Part[Position[groups, secondPart, 2], 1, 1];
If[fPAddress != sPAddress,
groups = ReplacePart[groups, fPAddress ->
Union[
Part[groups, fPAddress],
Part[groups, sPAddress]
]
];
groups = Delete[groups, sPAddress];
]