if statement - Python Counter doesn't count -


import urllib2 f=urllib2.urlopen("http://www.mbnet.com.pl/dl.txt") list = range(1,50) counter={}  lines in f:     tab_lines=lines.split(" ")     formated_tab=tab_lines[-1].strip().split(',')     #print formated_tab     in formated_tab:         if in list:             counter[i]+=1 print counter.items() 

my counter doesn't work , don't know why :(

this list of lottery numbers. count how many times drawn each number.

instead of using:

counter[i] = counter.get(i, 0) + 1 

you can try collections.defaultdict:

counter = defaultdict(int) 

so final version should this:

import urllib2 collections import defaultdict  f=urllib2.urlopen("http://www.mbnet.com.pl/dl.txt") list = range(1,50) counter=defaultdict(int)  # use defaultdict here  lines in f:     tab_lines=lines.split(" ")     formated_tab=tab_lines[-1].strip().split(',')     in formated_tab:         if int(i) in list:             counter[i] += 1  # don't worry, happy :) sumall=sum(counter.values()) number, value in counter.items():     print ('number {} drawn {} times , {}% of all').format(number,value,100*value/sumall) 

i'll give example show collections.defaultdict here:

>>> collections import defauldict >>> = {} >>> 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 subclass of built-in dict class, don't scared, can more it. once specified default_factory variable, when key not exist, defaultdict supply 1 according default_factory. note magic happen when using dict['key'] or dict.__getitem__(key).

the doucumetaion here: collections.defaultdict


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -