python中实现计数的方法

发布时间:2020-07-06 16:07:18 作者:清晨
来源:亿速云 阅读:429

这篇文章主要介绍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 = {}
for item in test_lst:if item in counter_dict: counter_dict[item] += 1 else: 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 = {}for item in test_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是自带“轮子”,就不用重新创造了,节省开发时间哦。

实例演示

from collections import defaultdict
test_lst = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'a', 'f', 's', 'b', 'h', 'k', 'i', 'j', 'c', 'd', 'f']
counter_ddict = defaultdict(int)for item in test_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)for item in temp: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中实现计数的方法的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. python如何计数
  2. Java实现计数排序的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:Django 分页

下一篇:解决sublime运行python提示错误的方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》