dict comprehension question.

Terry Reedy tjreedy at udel.edu
Sun Dec 30 00:22:20 CET 2012


On 12/29/2012 4:40 PM, Mitya Sirenef wrote:
> On 12/29/2012 03:15 PM, Joel Goldstick wrote:

>> Would this help:
>>
>>      >>> 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..

It still turns an O(n) problem into an O(k*n) problem, where k is the 
number of distinct items.

-- 
Terry Jan Reedy




More information about the Python-list mailing list