Python 列表(list) 统计元素出现的次数是有多种方式的,这里分别介绍这几种方法是如何在Python列表中统计元素出现的次数的。

使用 list.count() 方法统计

我们可以使用列表的内置方法list.count()统计某个元素出现的次数。

#!/usr/bin/python
# coding=utf-8

lst=[10, 20, 10, 30, 50, 60, 30, 45, 30, 80]
print(lst.count(30))  # 输出:3
print(lst.count(10))  # 输出:2
print(lst.count(80))  # 输出:1

上面的例子中,我们只能统计某一个元素出现的次数。

统计列表中每个项目的出现次数

我们可以使用双重for循环统计列表中每一个元素出现的次数,看下面的例子:
#!/usr/bin/python
# coding=utf-8
lst=[10, 20, 10, 30, 50, 60, 30, 45, 30, 80]

d={}
for i in range(len(lst)-1):
    x=lst[i]
    c=0
    for j in range(i,len(lst)):
        if lst[j]==lst[i]:
            c=c+1
    count=dict({x:c})
    if x not in d.keys():
        d.update(count)
print (d)
输出:
{10: 2, 20: 1, 30: 3, 50: 1, 60: 1, 45: 1}

 虽然可以实现我们的需求,但是两个for循环的方法显得有点有点繁琐,我们可以先获取到一个不重复的列表对象。

#!/usr/bin/python
# coding=utf-8
nums=[10, 20, 10, 30, 50, 60, 30, 45, 30, 80]
numsSet=set(nums) #去重
d={num:nums.count(num) for num in numsSet}
print(d) 
输出:
{10: 2, 45: 1, 80: 1, 50: 1, 20: 1, 60: 1, 30: 3}

使用Counter计数器方法

#!/usr/bin/python
# coding=utf-8
from collections import Counter

nums=[10, 20, 10, 30, 50, 60, 30, 45, 30, 80]
c=Counter(nums)
print (c)
d = dict(c) #转为字典
print (d) 
输出:

Counter({30: 3, 10: 2, 20: 1, 50: 1, 60: 1, 45: 1, 80: 1})
{10: 2, 20: 1, 30: 3, 50: 1, 60: 1, 45: 1, 80: 1}