【问题标题】:count each element in list without .count计算列表中没有 .count 的每个元素
【发布时间】:2012-11-16 03:21:28
【问题描述】:

对于这个函数,我想计算每个元素的出现次数并返回一个字典。 如:[a,b,a,c,b,a,c] 并返回 {a:3,b:2,c:2} 该怎么做?

【问题讨论】:

  • 到目前为止你的代码是什么样子的?
  • new_dict = {} count = 0 index = 0 for a in range(len(b)): if b[index] == b[index +1]: count += 1 index += 1 new_dict.update({a:count}) 返回 new_dict

标签: python list count


【解决方案1】:

然后你可以使用Counter

from collections import Counter
Counter( ['a','b','a','c','b','a','c'] )

DefaultDict:

from collections import defaultdict
d = defaultdict(int)
for x in lVals:
    d[x] += 1

或者:

def get_cnt(lVals):
    d = dict(zip(lVals, [0]*len(lVals)))
    for x in lVals:
        d[x] += 1
    return d   

【讨论】:

  • 谢谢。顺便说一句,我可以只创建一个函数而不导入任何东西吗?
  • 使用普通字典 - 如果字典中没有该值,则创建它然后递增它。
【解决方案2】:

使用内置类Counter

import collections
collections.Counter(['a','a','b'])

【讨论】:

  • 谢谢,但Artsiom先回答,所以我会用他的回答:)
【解决方案3】:

你可以使用dict.setdefault:

In [4]: def my_counter(lis):
    dic={}
    for x in lis:
        dic[x]=dic.setdefault(x,0)+1
    return dic
   ...: 

In [5]: my_counter(['a','b','a','c','b','a','c'])
Out[5]: {'a': 3, 'b': 2, 'c': 2}

dict.get:

In [10]: def my_counter(lis):
    dic={}
    for x in lis:
        dic[x]=dic.get(x,0)+1
    return dic
   ....: 

In [11]: my_counter(['a','b','a','c','b','a','c'])
Out[11]: {'a': 3, 'b': 2, 'c': 2}

【讨论】:

    猜你喜欢
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多