Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #44321

Re: Pythonic way to count sequences

References <bfc57a5f-bbcb-46a4-b59a-e7fa55527da1@y12g2000yqb.googlegroups.com>
Date 2013-04-25 15:26 +1000
Subject Re: Pythonic way to count sequences
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.1051.1366867611.3114.python-list@python.org> (permalink)

Show all headers | View raw


On Thu, Apr 25, 2013 at 3:05 PM, CM <cmpython@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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Pythonic way to count sequences CM <cmpython@gmail.com> - 2013-04-24 22:05 -0700
  Re: Pythonic way to count sequences Chris Angelico <rosuav@gmail.com> - 2013-04-25 15:26 +1000
    Re: Pythonic way to count sequences CM <cmpython@gmail.com> - 2013-04-25 19:40 -0700
  Re: Pythonic way to count sequences Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-04-25 06:14 +0000
  Re: Pythonic way to count sequences Serhiy Storchaka <storchaka@gmail.com> - 2013-04-25 15:36 +0300
  Re: Pythonic way to count sequences Denis McMahon <denismfmcmahon@gmail.com> - 2013-04-25 23:29 +0000
    Re: Pythonic way to count sequences Modulok <modulok@gmail.com> - 2013-04-25 19:16 -0600
    Re: Pythonic way to count sequences Matthew Gilson <m.gilson1@gmail.com> - 2013-04-25 22:40 -0400

csiph-web