而不是使用:
counter[i] = counter.get(i, 0) + 1
您也可以嘗試collections.defaultdict
:
counter = defaultdict(int)
所以,你最終版本應該是這個樣子:
import urllib2
from collections import defaultdict
f=urllib2.urlopen("http://www.mbnet.com.pl/dl.txt")
list = range(1,50)
counter=defaultdict(int) # use defaultdict here
for lines in f:
tab_lines=lines.split(" ")
formated_tab=tab_lines[-1].strip().split(',')
for i in formated_tab:
if int(i) in list:
counter[i] += 1 # don't worry, be happy :)
sumall=sum(counter.values())
for number, value in counter.items():
print ('Number {} drawn {} times and it is {}% of all').format(number,value,100*value/sumall)
我我會給你一個例子來展示什麼collections.defaultdict
在這裏所做的:
>>> from collections import defauldict
>>> a = {}
>>> a['notexist']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'notexist'
>>> b = defaultdict(int)
>>> b['notexist']
0
class collections.defaultdict([default_factory[, ...]])
defaultdict是內置的dict類,所以不要害怕一個子類,但你可以用它做更多。一旦您指定了default_factory
變量,當密鑰不存在時,defaultdict
將根據default_factory
爲您提供一個。請注意,只有當您使用dict['key']
或dict.__getitem__(key)
時,纔會發生這種魔術。
的doucumetaion是在這裏:collections.defaultdict
不要使用列表作爲變量名。 –