[Tutor] Possible with list comprehension?

Kent Johnson kent37 at tds.net
Sun Dec 24 22:15:57 CET 2006

Stewart Midwinter wrote:
> List comprehension is a wondering feature, well covered in diveintopython.org. I learned some new tricks there, especially from example 8.15.  Now I'm wondering if I can express the following more succinctly using list comprehension:
> for key,val in dataDict.items():
>     for i in range(val):
>         prods.append(key) 

I think this will do it:
prods = [ key for key,val in dataDict.items() for i in range(val) ]
> I have a dictionary containing an x,y set of values and occurrences:
> {'1':1, '10':2, '100':3, '1000':1, '10000':2} and want to find the mean value, so I need to build a list containing an occurrence weight set of values, and then select the middle value in the list. The list created by the above code snippet will look like this:
> [1, 10,10, 100,100,100, 1000, 10000,10000]
> and it has 9 elements, so the mean will be the 4.5th (call it 4th) element, so mean = 100. 

That is the median, not the mean. For this approach to work you have to 
sort dataDict.items(), in general dict keys and values are not in any 
obvious order. Fortunately it is easy to do this:
prods = [ key for key,val in sorted(dataDict.items()) for i in range(val) ]

> My attempt at the list comprehension is complicated by the fact that
I'm trying to add elements to the list that's under construction in the
list comprehension.

That is what every list comprehension does - it builds a new list, 
adding elements to the list that is under construction.


More information about the Tutor mailing list