Pythonic way to count sequences

Modulok modulok at gmail.com
Thu Apr 25 21:16:11 EDT 2013


On 4/25/13, Denis McMahon <denismfmcmahon at gmail.com> wrote:
> 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.
...

Consider using the ``collections`` module::


    from collections import Counter

    mylist = [(2,4), (2,4), (3,4), (4,5), (2,1)]
    count = Counter()
    for k in mylist:
        count[k] += 1

    print(count)

    # Output looks like this:
    # Counter({(2, 4): 2, (4, 5): 1, (3, 4): 1, (2, 1): 1})


You then have access to methods to return the most common items, etc. See more
examples here:

http://docs.python.org/3.3/library/collections.html#collections.Counter


Good luck!
-Modulok-



More information about the Python-list mailing list