4种Python统计次数的方法

本文介绍了如何使用Python的字典(dict)、collections.defaultdict、List的count方法以及集合(set)来统计可迭代对象中元素的出现次数,展示了不同的数据结构在计数操作中的应用。
摘要由CSDN通过智能技术生成

一、使用字典 dict 统计
循环遍历出一个可迭代对象的元素,如果字典中没有该元素,那么就让该元素作为字典的键,并将该键赋值为1,如果存在则将该元素对应的值加1

lists = ['a','a','b',1,2,3,1]
count_dist = dict()
for i in lists:
    if i in count_dist:
        count_dist[i] += 1
    else:
        count_dist[i] = 1
print(count_dist)
# {'a': 2, 'b': 1, 1: 2, 2: 1, 3: 1}

二、使用 collections.defaultdict 统计
defaultdict(parameter) 接受一个类型参数,例如:int、float、str 等。

传递进来的类型参数,不是用来约束值的类型,更不是约束键的类型,而是当键不存在时,实现一种值的初始化。

defaultdict(int) – 初始化为0
defaultdict(float) – 初始化为0.0
defaultdict(str) – 初始化为’’

from collections import defaultdict
lists = ['a','a','b',1,2,3,1]
count_dict = defaultdict(int)
for i in lists:
    count_dict[i] += 1
print(count_dict)
# defaultdict(<class 'int'>, {'a': 2, 'b': 1, 1: 2, 2: 1, 3: 1})

三、List count方法
统计List中每一个对象次数

test = ["aaa","bbb","aaa","aaa","ccc","ccc","ddd","aaa","ddd","eee","ddd"]
print(test.count("aaa"))
# 4
print(test.count("bbb"))
# 1

test_result = []
for i in test:
    if i not in test_result:
        test_result.append(i)
print(test_result)

for i in test_result:
    print(f"{i}:{test.count(i)}")

'''
4
1
['aaa', 'bbb', 'ccc', 'ddd', 'eee']
aaa:4
bbb:1
ccc:2
ddd:3
eee:1
'''

四、使用集合(set)和列表(list)统计
先用 set 去重,然后循环把每一个元素和对应的次数 list.count(item) 组成元组。

lists = ['a','a','b',1,2,3,1]
count_set = set(lists)
print(count_set) # 集合去重
# {1, 2, 3, 'b', 'a'}

count_list = list()
for i in count_set:
    count_list.append((i, lists.count(i)))
print(count_list)    
# [(1, 2), (2, 1), (3, 1), ('b', 1), ('a', 2)]

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

'Steven

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值