python 统计数组中元素的出现次数

如果只需要统计某个元素出现的次数,可直接使用count函数实现,
代码如下:

my_list = [1, 2, 2, -1, 4, 4, 4, 4, 5, 6, -1]
print(my_list.count(-1))

如果要返回每个元素出现的次数,可以使用如下两种方法:

方法一:

from collections import Counter
my_list = [1, 2, 2, -1, 4, 4, 4, 4, 5, 6, -1]
counter = Counter(my_list)
print(counter)
# 也可转为字典类型
print(dict(counter))

输出结果如下:

Counter({
    
    4: 4, 2: 2, -1: 2, 1: 1, 5: 1, 6: 1})
{
    
    1: 1, 2: 2, -1: 2, 4: 4, 5: 1, 6: 1}

方法二:

my_list = [1, 2, 2, -1, 4, 4, 4, 4, 5, 6, -1]
result = {
    
    }
for value in set(my_list):
  result[value] = my_list.count(value)
print(result)

输出结果:

{
    
    1: 1, 2: 2, 4: 4, 5: 1, 6: 1, -1: 2}

两种方法输出的元素顺序不同。

猜你喜欢

转载自blog.csdn.net/JingpengSun/article/details/130943398