My input consists of a list of lists (not necessary of the same length), like
[
['a', 'b', 'c', 'd', 'b'],
['a', 'd', 'e', 'b'],
['f', 'a', 'g', 'e', 'b', 'h']
]
and I would like to have a matrix / dictionary that contains the co-occurences. The keys of the dictionary are the elements of the original matrix, while the values would be a counter. So in the previous example, the result would be
{
'a' : Counter({'b': 4, 'c': 1, 'd': 2, 'e' : 2, 'f' : 1, 'g' : 1, 'h' : 1})
...
}
Here is my code:
import collections
def my_func(data):
result = collections.defaultdict(collections.Counter)
for l in data:
for e in l:
result[e].update([el for el in l if el is not e])
return result
my_func(data)
This works, except the fact I am not sure it's the smartest way: when updating the Counter, I am relooping over the elements of l
.
EDIT: I should probably clarify that the elements in the list are not necessary char
s but Python objects. I have used single letters only for faster typing.
el for el in l if el is not e
doesn't read very well! \$\endgroup\$