这会产生 3 个列表之间元组频率的计数,是否可以通过直接计数而不是增量计数(不是+=)来完成?为了澄清起见,我想解决必须使用+=并直接将计数应用于相应对来增加每次迭代的键值from collections import defaultdictfrom itertools import combinationsdd = 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] += 1defaultdict(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})
1 回答
波斯汪
TA贡献1811条经验 获得超4个赞
计数不会存储在任何地方,因此迭代是不可避免的。但是您可以使用collections.Counter生成器表达式来避免显式for循环:
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)))
结果:
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})
添加回答
举报
0/150
提交
取消