3 回答

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超6個(gè)贊
在2.7和3.1中Counter,為此目的有一個(gè)特殊的命令。
>>> from collections import Counter
>>> Counter(['apple','red','apple','red','red','pear'])
Counter({'red': 3, 'apple': 2, 'pear': 1})

TA貢獻(xiàn)1807條經(jīng)驗(yàn) 獲得超9個(gè)贊
我喜歡:
counts = dict()
for i in items:
counts[i] = counts.get(i, 0) + 1
如果密鑰不存在,.get允許您指定默認(rèn)值。

TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超7個(gè)贊
>>> L = ['apple','red','apple','red','red','pear']
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for i in L:
... d[i] += 1
>>> d
defaultdict(<type 'int'>, {'pear': 1, 'apple': 2, 'red': 3})
添加回答
舉報(bào)