dict comprehension question.

Joel Goldstick joel.goldstick at gmail.com
Sun Dec 30 05:10:39 CET 2012


On Sat, Dec 29, 2012 at 7:26 PM, Tim Chase <python.list at tim.thechases.com>wrote:

> On 12/29/12 15:40, Mitya Sirenef wrote:
>
>>       >>> w = [1,2,3,1,2,4,4,5,6,1]
>>>       >>> s = set(w)
>>>       >>> s
>>>       set([1, 2, 3, 4, 5, 6])
>>>       >>> {x:w.count(x) for x in s}
>>>       {1: 3, 2: 2, 3: 1, 4: 2, 5: 1, 6: 1}
>>>
>>
>> Indeed, this is much better -- I didn't think of it..
>>
>
> Except that you're still overwhelmed by iterating over every element in
> "w" for every distinct element.  So you've gone from O(N**2) to O(k*N).
>
> The cleanest way to write it (IMHO) is MRAB's
>
>
>  >>> w = [1, 2, 3, 1, 2, 4, 4, 5, 6, 1]
>  >>> from collections import Counter
>  >>> results = dict(Counter(w))
>
> which should gather all the statistics in one single pass across "w"
> making it O(N), and it's Pythonically readable.
>
> -tkc
>
> I like this too.  I haven't learned about collections module yet.  Thanks
for the pointer

>
>
> --
> http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list>
>



-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20121229/fd3961e3/attachment.html>


More information about the Python-list mailing list