5种Python统计次数的方法

一、使用字典 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方法

count() 方法用于统计某个元素在列表中出现的次数。

使用语法

# 使用语法
list.count(obj) # 返回次数

统计单个对象次数

# 统计单个对象次数
aList = [123, 'abc', 'good', 'abc', 123]
print("Count for 123 :", aList.count(123))
print("Count for abc :", aList.count('abc'))
# Count for 123 : 2
# Count for abc : 2

统计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) 组成元组。

'''
学习中遇到问题没人解答?小编创建了一个Python学习交流群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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)]

五、collections.Counter方法

Counter 是一个容器对象,使用 collections 模块中的 Counter 类可以实现 hash 对象的统计。

Counter 是一个无序的容器类型,以字典的键值对形式存储,其中元素作为 key,其计数作为 value。

计数值可以是任意的 Interger(包括0和负数)。

Counter() 对象还有几个可调用的方法:

  • most_common(n) -- TOP n 个出现频率最高的元素
  • elements -- 获取所有的键 通过list转化
  • update -- 增加对象
  • subtrct -- 删除对象
  • 下标访问 a['xx'] --不存在时返回0
import collections
c = collections.Counter('helloworld')

直接显示各个元素频次

print(c)
# Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, 'w': 1, 'r': 1, 'd': 1})

使用 most_common 显示最多的n个元素

当多个元素计数值相同时,排列是无确定顺序的。

print(c.most_common(3))
# [('l', 3), ('o', 2), ('h', 1)]

使用数组下标获取,类似字典方式

print("The number of 'o':", c['o'])
# The number of 'o': 2

统计列表(只要列表中对象都是可以哈希的)

import collections
x = [1,2,3,4,5,6,7,8,1,8,8,8,4,3,5]
c = collections.Counter(x)
print(c)
# Counter({1: 2, 2: 1, 3: 2, 4: 2, 5: 2, 6: 1, 7: 1, 8: 4})
print(c.most_common(3))
# [(8, 4), (1, 2), (3, 2)]
dictc = dict(c) # 转换为字典
print(dictc)
# {1: 2, 2: 1, 3: 2, 4: 2, 5: 2, 6: 1, 7: 1, 8: 4}

如果列表中有 unhashalbe 对象,例如:可变的列表,是无法统计的。

元组也可以统计。

c = collections.Counter([[1,2], "hello", 123, 0.52])
# TypeError: unhashable type: 'list'

得到 Counter 计数器对象之后,还可以在此基础上进行增量更新。

elements() -- 返回迭代器

元素排列无确定顺序,个数小于1的元素不被包含。

'''
学习中遇到问题没人解答?小编创建了一个Python学习交流群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import collections
c = collections.Counter(a=4,b=2,c=1)
print(c)
# Counter({'a': 4, 'b': 2, 'c': 1})

list(c.elements())
# ['a', 'a', 'a', 'a', 'b', 'b', 'c']

subtract函数 -- 减去元素

import collections
c = collections.Counter(["a","b","c","a"])
print(c)
# Counter({'a': 2, 'b': 1, 'c': 1})
print(list(c.elements())) # 展开
# ['a', 'a', 'b', 'c']

# 减少元素
c.subtract(["a","b"])
print(c)
# Counter({'a': 1, 'c': 1, 'b': 0})
print(list(c.elements()))
# ['a', 'c']

update函数 -- 增加元素

在进行增量计数时候,update函数非常有用。

'''
学习中遇到问题没人解答?小编创建了一个Python学习交流群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import collections
c = collections.Counter(["a","b","c","a"])
print(c)
# Counter({'a': 2, 'b': 1, 'c': 1})
print(list(c.elements())) # 展开
# ['a', 'a', 'b', 'c']

c.update(["a","d"])
print(c)
# Counter({'a': 3, 'b': 1, 'c': 1, 'd': 1})
print(list(c.elements()))
# ['a', 'a', 'a', 'b', 'c', 'd']

del函数 -- 删除键

当计数值为0时,并不意味着元素被删除,删除元素应当使用del。

import collections
c = collections.Counter('helloworld')
print(c)
# Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, 'w': 1, 'r': 1, 'd': 1})

c["d"] = 0
print(c)
# Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, 'w': 1, 'r': 1, 'd': 0})

del c["l"]
print(c)
# Counter({'o': 2, 'h': 1, 'e': 1, 'w': 1, 'r': 1, 'd': 0})

结尾给大家推荐一个非常好的学习教程,希望对你学习Python有帮助!

Python基础入门教程推荐:更多Python视频教程-关注B站:Python学习者
https://www.bilibili.com/video/BV1LL4y1h7ny?share_source=copy_web

Python爬虫案例教程推荐:更多Python视频教程-关注B站:Python学习者
https://www.bilibili.com/video/BV1QZ4y1N7YA?share_source=copy_web

原文地址:https://www.cnblogs.com/python960410445/p/15435330.html