Pythonic way to count sequences

Denis McMahon denismfmcmahon at gmail.com
Thu Apr 25 19:29:28 EDT 2013


On Wed, 24 Apr 2013 22:05:52 -0700, CM wrote:

> I have to count the number of various two-digit sequences in a list such
> as this:
> 
> mylist = [(2,4), (2,4), (3,4), (4,5), (2,1)]  # (Here the (2,4) sequence
> appears 2 times.)
> 
> and tally up the results, assigning each to a variable.  The inelegant
> first pass at this was something like...
> 
> # Create names and set them all to 0 alpha = 0 beta = 0 delta = 0 gamma
> = 0 # etc...
> 
> # loop over all the tuple sequences and increment appropriately for
> sequence_tuple in list_of_tuples:
>     if sequence_tuple == (1,2):
>         alpha += 1
>     if sequence_tuple == (2,4):
>         beta += 1
>     if sequence_tuple == (2,5):
>         delta +=1
> # etc... But I actually have more than 10 sequence types.
> 
> # Finally, I need a list created like this:
> result_list = [alpha, beta, delta, gamma] #etc...in that order
> 
> I can sense there is very likely an elegant/Pythonic way to do this, and
> probably with a dict, or possibly with some Python structure I don't
> typically use.  Suggestions sought.  Thanks.

mylist = [ (3,3), (1,2), "fred", ("peter",1,7), 1, 19, 37, 28.312, 
("monkey"), "fred", "fred", (1,2) ]

bits = {}

for thing in mylist:
	if thing in bits:
		bits[thing] += 1
	else:
		bits[thing] = 1

for thing in bits:
	print thing, " occurs ", bits[thing], " times"

outputs:

(1, 2)  occurs  2  times
1  occurs  1  times
('peter', 1, 7)  occurs  1  times
(3, 3)  occurs  1  times
28.312  occurs  1  times
fred  occurs  3  times
19  occurs  1  times
monkey  occurs  1  times
37  occurs  1  times

if you want to check that thing is a 2 int tuple then use something like:

for thing in mylist:
	if isinstance( thing, tuple ) and len( thing ) == 2 and isinstance
( thing[0], ( int, long ) ) and isinstance( thing[1], ( int, long) ):
		if thing in bits:
			bits[thing] += 1
		else:
			bits[thing] = 1

-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list