您可以将collections.defaultdict 与frozenset 和itertools.combinations 一起使用来形成成对计数的字典。
变化是可能的。例如,您可以使用 collections.Counter 和 sorted tuple,但基本相同。
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})