python中对列表的元素进行计数

 

001、方法1  借助字典统计

[root@pc1 test2]# ls
test.py
[root@pc1 test2]# cat test.py              ## 测试程序
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

list1 = ["aa", "bb", "aa", "cc", "aa", "dd", "dd", "ee"]    ## 测试列表
dict1 = {}                                                  ## 空字典

for i in list1:
        if i not in dict1:
                dict1[i] = 1
        else:
                dict1[i] += 1

for i,j in dict1.items():
        print(i, j)
[root@pc1 test2]# python3 test.py     ## 统计计数
aa 3
bb 1
cc 1
dd 2
ee 1

 

 

002、方法2,借助内置函数

a、

[root@pc1 test2]# ls
test.py
[root@pc1 test2]# cat test.py               ## 测试程序
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

list1 = ["aa", "bb", "aa", "cc", "aa", "dd", "dd", "ee"]
list2 = []

for i in list1:
        if i not in list2:
                list2.append(i)

for i in list2:
        print(i, list1.count(i))
[root@pc1 test2]# python3 test.py          ## 执行程序
aa 3
bb 1
cc 1
dd 2
ee 1

 

b、如果输出顺序无要求,可以使用集合去重复

[root@pc1 test2]# ls
test.py
[root@pc1 test2]# cat test.py           ## 测试程序
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

list1 = ["aa", "bb", "aa", "cc", "aa", "dd", "dd", "ee"]

for i in set(list1):                     ## 集合去重复
        print(i, list1.count(i))
[root@pc1 test2]# python3 test.py         ## 执行程序
aa 3
cc 1
ee 1
bb 1
dd 2

 

003、方法3

借助Counter 模块

[root@pc1 test2]# ls
test.py
[root@pc1 test2]# cat test.py                  ## 测试程序
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from collections import Counter

list1 = ["aa", "bb", "aa", "cc", "aa", "dd", "dd", "ee"]

dict1 = dict(Counter(list1))
print(dict1)
[root@pc1 test2]# python3 test.py              ## 执行程序
{'aa': 3, 'bb': 1, 'cc': 1, 'dd': 2, 'ee': 1}

 。

 

posted @ 2023-09-30 23:26  小鲨鱼2018  阅读(50)  评论(0编辑  收藏  举报