本文实例展示了Python统计列表中的重复项出现的次数的方法,是一个很实用的功能,适合Python初学者学习借鉴。具体方法如下:
方法1:
str ='''Error response from daemon: conflict: unable to remove repository reference "ubuntu" (must force) - container 40d59b73842b is using its referenced image 14f60031763d'''
mylist = list(str)
myset = set(mylist)
# print mylist
# print myset
max = 0
# print fcflist
for item in myset:
print(item, mylist.count(item))
if(max < mylist.count(item)):
max = mylist.count(item)
print max
运行结果如下
C:\Python27\python.exe D:/healthcode/tongjistr.py
(' ', 21)
('"', 2)
(')', 1)
('(', 1)
('-', 1)
('1', 2)
('0', 3)
('3', 3)
('2', 1)
('5', 1)
('4', 3)
('7', 2)
('6', 2)
('9', 1)
('8', 1)
(':', 2)
('E', 1)
('a', 4)
('c', 6)
('b', 4)
('e', 18)
('d', 4)
('g', 2)
('f', 6)
('i', 7)
('m', 5)
('l', 2)
('o', 11)
('n', 10)
('p', 2)
('s', 7)
('r', 14)
('u', 6)
('t', 7)
('v', 1)
('y', 1)
21
进程已结束,退出代码0
方法2:
利用字典的特性来实现
str ='''Error response from daemon: conflict: unable to remove repository reference "ubuntu" (must force) - container 40d59b73842b is using its referenced image 14f60031763d'''
list = list(str)
# print list
a = {}
for i in list:
if list.count(i) > 1:
a[i] = list.count(i)
print (a)
C:\Python27\python.exe D:/healthcode/tongji3.py
{' ': 21, '"': 2, '1': 2, '0': 3, '3': 3, '4': 3, '7': 2, '6': 2, ':': 2, 'a': 4, 'c': 6, 'b': 4, 'e': 18, 'd': 4, 'g': 2, 'f': 6, 'i': 7, 'm': 5, 'l': 2, 'o': 11, 'n': 10, 'p': 2, 's': 7, 'r': 14, 'u': 6, 't': 7}
进程已结束,退出代码0
方法3:
l=[1,4,2,4,2,2,5,2,6,3,3,6,3,6,6,3,3,3,7,8,9,8,7,0,7,1,2,4,7,8,9]
count_times = []
for i in l:
count_times.append(l.count(i))
m = max(count_times)
n = l.index(m)
print (l[n])
C:\Python27\python.exe D:/healthcode/tongji3.py
6
进程已结束,退出代码0