目录
  • 一、使用字典 dict 统计
  • 二、使用 collections.defaultdict 统计
  • 三、list count方法
  • 四、使用集合(set)和列表(list)统计
  • 五、collections.counter方法

一、使用字典 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) 组成元组。

'''
学习中遇到问题没人解答?www.887551.com创建了一个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的元素不被包含。

'''
学习中遇到问题没人解答?www.887551.com创建了一个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函数非常有用。

'''
学习中遇到问题没人解答?www.887551.com创建了一个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})

到此这篇关于5种python统计次数方法技巧的文章就介绍到这了,更多相关python内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!