[“ A”,“ A”,“ A”,“ B”,“ B”,“ B”]的列表
的词典 {'A':3, 'B':3}
我已经做了下面的事情,但是我感觉有更快/更短的方法吗?
frequencyMap = dict()
letters = ["A","A","A","B","B","B"]
for letter in letters:
if letter not in frequencyMap:
frequencyMap[letter] = 0
frequencyMap[letter] += 1
答案 0 :(得分:1)
在Python 2.7(或更高版本)中,您可以使用collections.Counter
collections.Counter()
计数器是一个将元素存储为字典键的容器,它们的计数存储为字典值。
import collections
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
counter=collections.Counter(a)
print(counter)
# Counter({1: 4, 2: 4, 3: 2, 5: 2, 4: 1})
答案 1 :(得分:1)
from collections import Counter
print(Counter(["A","A","A","B","B","B"]))