Pythonic way to count sequences
Chris Angelico
rosuav at gmail.com
Thu Apr 25 01:26:48 EDT 2013
On Thu, Apr 25, 2013 at 3:05 PM, CM <cmpython at gmail.com> 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.
You can use a tuple as a dictionary key, just like you would a string.
So you can count them up directly with a dictionary:
count = {}
for sequence_tuple in list_of_tuples:
count[sequence_tuple] = count.get(sequence_tuple,0) + 1
Also, since this is such a common thing to do, there's a standard
library way of doing it:
import collections
count = collections.Counter(list_of_tuples)
This doesn't depend on knowing ahead of time what your elements will
be. At the end of it, you can simply iterate over 'count' and get all
your counts:
for sequence,number in count.items():
print("%d of %r" % (number,sequence))
ChrisA
More information about the Python-list
mailing list