0

I have a list of arrays that go like:

[array(['A2', 'A1'], dtype=object),
 array(['A2', 'A3'], dtype=object),
 array(['A2', 'A4'], dtype=object),
 array(['A1', 'A3'], dtype=object),
 array(['A1', 'A4'], dtype=object),
 array(['A3', 'A4'], dtype=object),
 array(['B2', 'B1'], dtype=object),
 array(['B2', 'B3'], dtype=object),
 array(['B1', 'B3'], dtype=object)]

I want to combine those arrays if one of the elements in an array is found in another array. And then remove the duplicate.

The expected outcome should go like:

[array['A1', 'A2', 'A3', 'A4'], array[B1', 'B2', 'B3']]

Any idea about how I can do this? Cheers!

2 Answers 2

1

It sounds like you want the connected components of a graph.

from numpy import array

edges = [
    array(['A2', 'A1'], dtype=object),
    array(['A2', 'A3'], dtype=object),
    array(['A2', 'A4'], dtype=object),
    array(['A1', 'A3'], dtype=object),
    array(['A1', 'A4'], dtype=object),
    array(['A3', 'A4'], dtype=object),
    array(['B2', 'B1'], dtype=object),
    array(['B2', 'B3'], dtype=object),
    array(['B1', 'B3'], dtype=object),
]

import networkx
G = networkx.Graph()
G.add_edges_from(edges)
print(list(networkx.connected_components(G)))
# [{'A1', 'A3', 'A4', 'A2'}, {'B2', 'B1', 'B3'}]

Demo: https://repl.it/repls/FluidPleasedScope

networkx documentation

Sign up to request clarification or add additional context in comments.

Comments

0

You can use, np.unique + itertools.groupby

from itertools import groupby
from numpy import array, unique

values = [
    array(['A2', 'A1'], dtype=object),
    array(['A2', 'A3'], dtype=object),
    array(['A2', 'A4'], dtype=object),
    array(['A1', 'A3'], dtype=object),
    array(['A1', 'A4'], dtype=object),
    array(['A3', 'A4'], dtype=object),
    array(['B2', 'B1'], dtype=object),
    array(['B2', 'B3'], dtype=object),
    array(['B1', 'B3'], dtype=object)
]

print([
    list(v) for _, v in groupby(unique(values), key=lambda x: x[0])
])

[['A1', 'A2', 'A3', 'A4'], ['B1', 'B2', 'B3']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.