Returning histogram-like data for items in a list

Ric Deez deez at next-level.com.au
Thu Jul 21 19:32:15 EDT 2005


Hi there,

I have a list:
L1 = [1,1,1,2,2,3]

How can I easily turn this into a list of tuples where the first element 
is the list element and the second is the number of times it occurs in 
the list (I think that this is referred to as a histogram):

i.e.:

L2 = [(1,3),(2,2),(3,1)]

I was doing something like:

myDict = {}
for i in L1:
	myDict.setdefault(i,[]).append(i)

then doing this:

L2 = []
for k, v in myDict.iteritems():
	L2.append((k, len(v)))

This works but I sort of feel like there ought to be an easier way, 
rather than to have to store the list elements, when all I want is a 
count of them. Would anyone care to comment?

I also tried this trick, where locals()['_[1]'] refers to the list 
comprehension itself as it gets built, but it gave me unexpected results:

 >>> L2 = [(i, len(i)) for i in L2 if not i in locals()['_[1]']]
 >>> L2
[((1, 3), 2), ((2, 2), 2), ((3, 1), 2)]

i.e. I don't understand why each tuple is being counted as well.

Regards,

Ric



More information about the Python-list mailing list