python统计list各元素出现的次数

  1. 方法一:字典统计
a = ['apple', 'orange', 'apple', 'dog', 'cat', 'dog']
dict = {}
for key in a:
    dict[key] = dict.get(key, 0) + 1
print(dict)

{‘apple’: 2, ‘orange’: 1, ‘dog’: 2, ‘cat’: 1}

  1. 方法二:collection包下Counter类统计
from collections import Counter
a = ['apple', 'orange', 'apple', 'dog', 'cat', 'dog']
result = Counter(a)
print(result)
print (type(result))

Counter({‘apple’: 2, ‘dog’: 2, ‘orange’: 1, ‘cat’: 1})

参考链接:[https://www.cnblogs.com/keye/p/9720694.html](https://www.cnblogs.com/keye/p/9720694.html)

你可能感兴趣的:(人生苦短,我用Python)