【问题标题】:Count how many times a part of a key appears in a dictionary python计算一个键的一部分出现在字典python中的次数
【发布时间】:2012-11-06 23:41:00
【问题描述】:

我有以下字典,我想计算键出现的次数,字典很大。

a = { (1,2):3, (1,3):5, (2,1):6 }

我想要这个结果

1: 3 times
2: 2 times
3: 1 time

【问题讨论】:

  • 键只能出现一次。你在数别的东西

标签: python list dictionary key tuples


【解决方案1】:

首先,这不是代码编写服务。试着先写一些,然后问一个问题。

其次,作为免费赠品,在 Python 中:

import collections
s = collections.defaultdict(int)
for j, k in a.keys():
   s[j] += 1
   s[k] += 1
for x in s.keys():
   print x + ": " + s[x] + " times"

【讨论】:

    【解决方案2】:

    使用itertoolscollections.defaultdict

    In [43]: a={(1,2):3,(1,3):5,(2,1):6}
    
    In [44]: counts = collections.defaultdict(int)
    
    In [45]: for k in itertools.chain.from_iterable(a.keys()):
       ....:     counts[k] += 1
       ....:     
    
    In [46]: for k in counts:
        print k, ": %d times" %counts[k]
       ....:     
    1 : 3 times
    2 : 2 times
    3 : 1 times
    

    【讨论】:

      【解决方案3】:
      from collections import Counter
      items = Counter(val[2] for val in dic.values())
      

      希望对它进行排序。

      【讨论】:

        【解决方案4】:

        使用itertools.chaincollections.Counter

        collections.Counter(itertools.chain(*a.keys()))
        

        或者:

        collections.Counter(itertools.chain.from_iterable(a.keys()))
        

        【讨论】:

        • 我是这个的忠实粉丝。不知道collections.Counter
        • collections.Counter打败我的方法!真希望我能想到这一点。此外,itertools.chain.from_iterable 将不再需要使用 *
        • itertools.chain.from_iterable() 绝对优于生成器表达式。
        【解决方案5】:
        >>> from collections import Counter
        >>> a = { (1,2):3, (1,3):5, (2,1):6 }
        >>> 
        >>> Counter(j for k in a for j in k)
        Counter({1: 3, 2: 2, 3: 1})
        

        【讨论】:

        • 每次我写这个特别的理解(扁平化)我都需要停下来想一想js、ks 和as 的顺序 :) 尽管如此,非常好的解决方案。
        【解决方案6】:

        使用python 3.2

        from collections import Counter
        from itertools import chain  
        
        res = Counter(list(chain(*a)))
        

        【讨论】:

        • 那里不需要listCounter 很乐意使用任何可迭代对象。
        猜你喜欢
        • 2015-09-06
        • 2019-07-13
        • 2018-06-30
        • 1970-01-01
        • 2022-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-11
        相关资源
        最近更新 更多