Python 直接计数,而不是增量计数解决方案

Python 直接计数,而不是增量计数解决方案,python,dictionary,combinations,counter,Python,Dictionary,Combinations,Counter,这会产生3个列表之间元组的频率计数,可以通过直接计数而不是增量计数(而不是+=)来完成吗 为了澄清,我想解决必须使用+=为每次迭代增加密钥值的问题,并直接将计数应用于相应的对 from collections import defaultdict from itertools import combinations dd = defaultdict(int) L1 = ["cat", "toe", "man"] L2 = ["cat", "toe", "ice"] L3 = ["cat",

这会产生3个列表之间元组的频率计数,可以通过直接计数而不是增量计数(而不是
+=
)来完成吗

为了澄清,我想解决必须使用
+=
为每次迭代增加密钥值的问题,并直接将计数应用于相应的对

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
计数不会存储在任何地方,因此迭代是不可避免的。但您可以将
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})
计数不会存储在任何地方,因此迭代是不可避免的。但您可以将
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})

“直接计数”是什么意思?你可以从用户级的源代码中混淆递增操作,但我不知道你打算如何在不递增的情况下得到总数。在过程中不使用
+=
直接将计数应用到所述对中,你说的“直接计数”是什么意思?您可以从用户级源代码中模糊增量操作,但是我不知道你打算如何在不增加任何值的情况下得到总数。在这个过程中不使用
+=
,直接将计数应用到所说的pairchain是一个很好的方法-你们两个都用了2分钟的时间得到了我。尽管在这个解决方案上存在激烈的竞争,但我喜欢这个
(计数器(元组(排序(对))对于组合中成对的l4中的子列表(子列表,2)))
链是一个很好的接触-你们两个都用了2分钟。对于这个解决方案,存在着激烈的竞争,尽管,我喜欢这个
(对于组合中成对的l4中的子列表(子列表,2))