2012-03-17 76 views
2

我尋找最優雅的方式來做到以下幾點:最優雅的方式在列表中算整數

比方說,我要計算時間每個整數出現在清單中的號碼;我能做到這樣:

x = [1,2,3,2,4,1,2,5,7,2] 

dicto = {} 

for num in x: 
    try: 
     dicto[num] = dicto[num] + 1 
    except KeyError: 
     dicto[num] = 1 

不過,我認爲

try: 
    dicto[num] = dicto[num] + 1 
except KeyError: 
    dicto[num] = 1 

是不是最優雅的方式來做到這一點;我認爲我看到上面的代碼被一行代替。什麼是最優雅的方式來做到這一點?

我意識到這可能是一個重複,但我環顧四周,找不到我在找什麼。

謝謝您提前。

回答

3
>>> from collections import defaultdict 
>>> x = [1,2,3,2,4,1,2,5,7,2] 
>>> d = defaultdict(int) 
>>> for i in x: 
     d[i] += 1 

>>> dict(d) 
{1: 2, 2: 4, 3: 1, 4: 1, 5: 1, 7: 1} 

或者只是collections.Counter,如果你是在Python 2.7+以上。

8

使用Counter類

>>> from collections import Counter 
>>> x = [1,2,3,2,4,1,2,5,7,2] 
>>> c = Counter(x) 

現在你可以使用Counter對象c作爲字典。

>>> c[1] 
2 
>>> c[10] 
0 

(這適用於不存在的值也是如此)

+0

這是最正確的,如果你想在'Counter'類的額外開銷:當你不需要從Counter的額外開銷這似乎是理想的。檢查源代碼,它確實支持'dict',使得散列查找和迭代性能理想。 – MrGomez 2012-03-17 22:32:51

1

Bucket sort,因爲你正在做的,是完全適當的算法(discussion)。

from collections import defaultdict 

wdict = defaultdict(int) 

for word in words: 
    wdict[word] += 1 
相關問題