python中统计列表元素出现的次数

 

>>> a = ["ee","cc","aa","ff","aa","cc","dd","ee","dd","ee","aa","aa","bb"]  ##生成列表
>>> a
['ee', 'cc', 'aa', 'ff', 'aa', 'cc', 'dd', 'ee', 'dd', 'ee', 'aa', 'aa', 'bb']
>>> a.count("aa")  ## 统计单个元素的次数
4
>>> a.count("bb")
1
>>> b = []
>>> for i in a:      ## 去重复
    if i not in b:
        b.append(i)

        
>>> b
['ee', 'cc', 'aa', 'ff', 'dd', 'bb']
>>> b.sort()        ## 排序
>>> b
['aa', 'bb', 'cc', 'dd', 'ee', 'ff']
>>> for i in b:     ## 统计所有元素的次数
    print(i,a.count(i))

    
aa 4
bb 1
cc 2
dd 2
ee 3
ff 1

 

posted @ 2021-02-24 08:31  小鲨鱼2018  阅读(377)  评论(0编辑  收藏  举报