Returning histogram-like data for items in a list

Michael Hoffman cam.ac.uk at mh391.invalid
Fri Jul 22 01:50:40 CEST 2005


Ric Deez wrote:
> 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)]

 >>> import itertools
 >>> L1 = [1,1,1,2,2,3]
 >>> L2 = [(key, len(list(group))) for key, group in itertools.groupby(L1)]
 >>> L2
[(1, 3), (2, 2), (3, 1)]
-- 
Michael Hoffman



More information about the Python-list mailing list