Reputation: 4606
This produces a count of frequency of tuples between 3 list, can it be done via direct count not incremental count (not +=
)?
For clarification, I would like to work around having to increase the value of the key for every iteration using +=
and directly apply the count to corresponding pair
from collections import defaultdict
from itertools import combinations
dd = defaultdict(int)
L1 = ["cat", "toe", "man"]
L2 = ["cat", "toe", "ice"]
L3 = ["cat", "hat", "bed"]
for L in [L1, L2, L3]:
for pair in map(frozenset, (combinations(L, 2))):
dd[pair] += 1
defaultdict(int, {frozenset({'cat', 'toe'}): 2, frozenset({'cat', 'man'}): 1, frozenset({'man', 'toe'}): 1, frozenset({'cat', 'ice'}): 1, frozenset({'ice', 'toe'}): 1, frozenset({'cat', 'hat'}): 1, frozenset({'bed', 'cat'}): 1, frozenset({'bed', 'hat'}): 1})
Upvotes: 0
Views: 84
Reputation: 164753
The counts are not stored anywhere, so iteration is unavoidable. But you can use collections.Counter
with a generator expression to avoid an explicit for
loop:
from collections import Counter
from itertools import chain, combinations
L1 = ["cat", "toe", "man"]
L2 = ["cat", "toe", "ice"]
L3 = ["cat", "hat", "bed"]
L_comb = [L1, L2, L3]
c = Counter(map(frozenset, chain.from_iterable(combinations(L, 2) for L in L_comb)))
Result:
Counter({frozenset({'cat', 'toe'}): 2,
frozenset({'cat', 'man'}): 1,
frozenset({'man', 'toe'}): 1,
frozenset({'cat', 'ice'}): 1,
frozenset({'ice', 'toe'}): 1,
frozenset({'cat', 'hat'}): 1,
frozenset({'bed', 'cat'}): 1,
frozenset({'bed', 'hat'}): 1})
Upvotes: 4