Pythonic way to count sequences

Matthew Gilson m.gilson1 at gmail.com
Thu Apr 25 22:40:36 EDT 2013


A Counter is definitely the way to go about this.  Just as a little more 
information.  The below example can be simplified:

     from collections import Counter
     count = Counter(mylist)

With the other example, you could have achieved the same thing (and been 
backward compatible to python2.5) with

    from collections import defaultdict
    count = defaultdict(int)
    for k in mylist:
         count[k] += 1



On 4/25/13 9:16 PM, Modulok wrote:
> 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