I have a data structure like this
[
(123, 321),
(123, 456),
(999, 654),
(111, 456),
(999, 898),
(111, 654),
(481, 739),
]
How can I group the tuples together by any matching element? i.e. to get this result (order doesn't matter)
[
[(123, 321), (123, 456), (111, 456), (111, 654), (999, 654), (999, 898)],
[(481, 739)],
]
Here's another example:
input =
[
(123, 321),
(123, 456),
(111, 456),
(999, 898),
(481, 898),
(481, 549),
]
output =
[
[(123, 321), (123, 456), (111, 456)],
[(999, 898), (481, 898), (481, 549)],
]
If I have understood the question correctly then you are trying to generate a list that contains two lists as follows:
If the above is the case then effectively which are looking to do is determine which values occur more than once and use this information to generate your lists.
One approach is to use Python's
Counterclass to count up the occurrences of each value. You can do this as follows:This will give you the following:
Next, you can iterate through your list of tuples and separate them based on whether the values in the tuple occur more than once or not:
This will then give you the desired result: