list comprehention

Bryan Olson fakeaddress at nowhere.org
Mon Jan 23 22:50:51 EST 2006


Bryan Olson wrote:
> Duncan Booth wrote:
> 
>> Here's the way I would do it:
>>
>>>>> def occurrences(it):
>>
>>
>>     res = {}
>>     for item in it:
>>         if item in res:
>>             res[item] += 1
>>         else:
>>             res[item] = 1
>>     return res
> 
> 
> I slightly prefer:
> 
> def occurrences(it):
>     res = {}
>     res[item] = res.get(item, 0) + 1
>     return res

Arg! In illustrating a trivial point, I dropped something essential.
This version has almost three minutes of testing behind it:

def occurrences(it):
     res = {}
     for item in it:
         res[item] = res.get(item, 0) + 1
     return res


-- 
--Bryan



More information about the Python-list mailing list