dict comprehension question.

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Dec 31 22:10:48 EST 2012


On Sat, 29 Dec 2012 18:56:57 -0500, Terry Reedy wrote:

> On 12/29/2012 2:48 PM, Quint Rankid wrote:
> 
>> Given a list like:
>> w = [1, 2, 3, 1, 2, 4, 4, 5, 6, 1]
>> I would like to be able to do the following as a dict comprehension. 
>> a = {}
>> for x in w:
>>      a[x] = a.get(x,0) + 1
>> results in a having the value:
>> {1: 3, 2: 2, 3: 1, 4: 2, 5: 1, 6: 1}
> 
> Let me paraphrase this: "I have nice, clear, straightforward,
> *comprehensible* code that I want to turn into an incomprehensible mess
> with a 'comprehension." That is the ironic allure of comprehensions.

But... but... one liner! ONE LINNNNNNEEEERRRRR!!!! Won't somebody think 
of the lines I'll save!!!!

*wink*


In case it's not obvious, I'm 100% agreeing with Terry here. List comps 
and dict comps are wonderful things, but they can't do everything, and 
very often even if they can do something they shouldn't because it makes 
the code inefficient or unreadable.

There's nothing wrong with a two or three liner.



-- 
Steven



More information about the Python-list mailing list