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

Count the assocations in a list of lists

I have a list of lists in python:

x=[['apple', 'banana', 'carrot'],['apple', 'banana'],['banana', 'carrot']]

I want to know the number of times two items are associated in an array.

My output would be like:

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

{['apple', 'banana']: 2, ['banana', 'carrot']: 2, ['apple', 'carrot']: 1}

I know how to count the occurrences of an item in a list of lists, but not too sure how to add a counter for the association of occurrences to the mix.

Does anyone have any ideas?

>Solution :

You can accomplish this with itertools and collections (both of which are in the standard library):

from collections import Counter
from itertools import combinations

x=[['apple', 'banana', 'carrot'],['apple', 'banana'],['banana', 'carrot']]
print(Counter(combo for sublist in x for combo in combinations(sublist , 2)))
# Counter({('apple', 'banana'): 2, ('banana', 'carrot'): 2, ('apple', 'carrot'): 1})

Here, whenever two items exist in one of the sublists, combinations spits them out as a pair, then Counter counts this pair.

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