Returning histogram-like data for items in a list

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Thu Jul 21 22:18:12 EDT 2005


Ric Deez a écrit :
> 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, 

If you don't care about order (but your solution isn't garanteed to 
preserve order either...):

L2 = dict([(item, L1.count(item)) for item in L1]).items()

But this may be inefficient is the list is large, so...

def hist(seq):
   d = {}
   for item in seq:
      if not item in d:
	d[item] = seq.count(item)
   return d.items()

> I also tried this trick, where locals()['_[1]'] refers to the list 

Not sure to understand how that one works... But anyway, please avoid 
this kind of horror unless your engaged in WORN context with a 
perl-monger !-).



More information about the Python-list mailing list