Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python aggregate lists that share a common item

I’m looking for a function to aggregate lists that have a common item. The specific example I had in mind was the following case:

inputs = [['a','b'], ['a','c'], ['b','d'], ['e','f'], ['g','h'], ['i','k'], ['k','l']]
aggregated_output = [['a','b','c','d'],['e','f'],['g','h'],['i','k','l']]

as you can see, all the lists that share a common item have been bunched together. The order of the lists or the items in the lists in the output does not matter.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Maybe Brute-Force Solutions help you:

inputs = [['a','b'], ['a','c'], ['b','d'], ['e','f'], ['g','h'], ['i','k'], ['k','l']]

res = []
for arr in inputs:
    flaq = False
    for r in res:
        for a in arr:
            if a in r:
                r += [a for a in arr if not a in r]
                flaq = True
                break
    if not flaq:
        res.append(arr)
print(res)

Output:

[['a', 'b', 'c', 'd'], ['e', 'f'], ['g', 'h'], ['i', 'k', 'l']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading