代码之家  ›  专栏  ›  技术社区  ›  vash_the_stampede

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

  •  0
  • vash_the_stampede  · 技术社区  · 6 年前

    这就产生了一个计数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
    
    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})
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   jpp    6 年前

    存储 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})