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:
{['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.