邢台wap网站建设,wordpress注册跳过邮箱验证码,北京市朝阳区,网站站点的建立python中实现计数的一般方法#xff1a;1、使用字典解决(dict)字典计数是最常用的计数方法#xff0c;逐个遍历数据结构中元素#xff0c;将元素作为键#xff0c;元素个数作为值进行统计#xff0c;依次加入字典中。实例演示test_lst [a, b, c, d, e, f, g, a, f, s, b,…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 defaultdicttest_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(, {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)]