0%

Python | 列表 List

统计列表中重复项出现的次数:

  1. collections.Counter()
  2. list.count()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from collections import Counter

lst = ['a', 'a', 'v', 'c', 'b', 'a', 'b', 'c', 'b']
Counter(lst)
# Counter({'a': 3, 'v': 1, 'c': 2, 'b': 3})


lst = ['a', 'a', 'v', 'c', 'b', 'a', 'b', 'c', 'b']
for item in set(lst):
print('the %s appears %d times' %(item, lst.count(item)))
#the c appears 2 times
#the v appears 1 times
#the a appears 3 times
#the b appears 3 times
Thank you for your approval.

欢迎关注我的其它发布渠道