python and list/dict comprehension -


i'm learning list/dict comprehension , i'm stuck!!!

i don't understand following...

i have program:

def histogram_for(word):     adict = dict()     c in word:         adict[c] = adict.get(c, 0) + 1     print adict     return adict  def histogram_dc(word):     adict = dict()     adict = {c: (adict.get(c, 0) + 1) c in word}     print adict     return adict  def histogram_lc(word):     adict = dict()     adict = dict([(c, (adict.get(c, 0) + 1)) c in word])     print adict     return adict   word = "football" histogram_for(word.lower()) histogram_dc(word.lower()) histogram_lc(word.lower()) 

and these results:

{'a': 1, 'b': 1, 'f': 1, 'l': 2, 'o': 2, 't': 1} {'a': 1, 'b': 1, 'f': 1, 'l': 1, 'o': 1, 't': 1} {'a': 1, 'b': 1, 'f': 1, 'l': 1, 'o': 1, 't': 1} 

why working 1 "for" method?

quite because while processing happening in _dc , _lc adict empty, while in _for it's being updated on each turn of for loop. comprehension can de-sugared for loop of own:

adict = dict() adict = {c: (adict.get(c, 0) + 1) c in word} 

becomes:

adict = dict() # handwaving python $newdict = {} c in word:     $newdict[c] = adict.get(c, 0) + 1 adict = $newdict 

use collections.counter (or for-loop version) if need keep track of set of keys , counts of occurrences.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -