这篇文章主要介绍python中实现计数的方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

python中实现计数的一般方法:

1、使用字典解决(dict)

字典计数是最常用的计数方法,逐个遍历数据结构中元素,将元素作为键,元素个数作为值进行统计,依次加入字典中。

实例演示

test_lst=['a','b','c','d','e','f','g','a','f','s','b','h','k','i','j','c','d','f']counter_dict={}foritemintest_lst:ifitemincounter_dict:counter_dict[item]+=1else:counter_dict[item]=1print(counter_dict)

程序运行结果>>>{'i': 1, 'a': 2, 's': 1, 'g': 1, 'b': 2, 'k': 1, 'h': 1, 'j': 1, 'c': 2, 'e': 1, 'd': 2, 'f': 3}

2、使用dict.setdefault(key, dvalue)方法解决

可以使用dict.setdefault()方式进行统计,比起直接使用dict,该方法不用使用if-else语句进行判断,且避免了KeyError异常。

实例演示

test_lst=['a','b','c','d','eshi','f','g','a','f','s','b','h','k','i','j','c','d','f']counter_sdict={}foritemintest_lst:counter_sdict[item]=counter_sdict.setdefault(item,0)+1print(counter_sdict)

程序运行结果>>>{'k': 1, 'e': 1, 'c': 2, 'a': 2, 'b': 2, 'd': 2, 'f': 3, 'g': 1, 's': 1, 'j': 1, 'i': 1, 'h': 1}

同dict方法,但程序的容错性比上面的方法要好,且数据量大时,该程序比使用dict的传统方法要节省时间。

3、使用defaultdict类解决

defaultdict类的初始化函数接受一个类型作为参数,当所访问的键不存在的时候,它自动实例化一个值作为默认值。使用defaultdict与使用dict的区别在于,defaultdict能够自动对获取结果进行排序,这就解决了我们后续排序的麻烦,并且defaushltdict是自带“轮子”,就不用重新创造了,节省开发时间哦。

实例演示

fromcollectionsimportdefaultdicttest_lst=['a','b','c','d','e','f','g','a','f','s','b','h','k','i','j','c','d','f']counter_ddict=defaultdict(int)foritemintest_lst:counter_ddict[item]+=1print(counter_ddict)

程序运行结果>>>defaultdict(<class 'int'>, {'k': 1, 'e': 1, 'c': 2, 'a': 2, 'b': 2, 'd': 2, 'f': 3, 'g': 1, 's': 1, 'j': 1, 'i': 1, 'h': 1})

4、结合使用set和list两种数据结构来解决

思路如下:首先,初始化一个set和一个列表list,获取序列中需要统计的元素;然后,依次遍历set中的内容,使用需要统计序列的cosut()方法,分别统计set中的内容并计入新列表中。

实例演示

test_lst=['a','b','c','d','e','f','g','a','f','s','b','h','k','i','j','c','d','f']r_lst=[]temp=set(test_lst)foritemintemp:r_lst.append((item,test_lst.count(item)))print(r_lst)

程序运行结果>>>[('j', 1), ('k', 1), ('a', 2), ('s', 1), ('d', 2), ('h', 1), ('f', 3), ('c', 2), ('e', 1), ('b', 2), ('i', 1), ('g', 1)]

以上是python中实现计数的方法的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!