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 模块
标签:aa,test2,python,dd,py,列表,计数,test,## From: https://www.cnblogs.com/liujiaxin2018/p/17738407.html