Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #44378
| Date | 2013-04-25 22:40 -0400 |
|---|---|
| From | Matthew Gilson <m.gilson1@gmail.com> |
| Subject | Re: Pythonic way to count sequences |
| References | <bfc57a5f-bbcb-46a4-b59a-e7fa55527da1@y12g2000yqb.googlegroups.com> <klce8o$2pp$4@dont-email.me> <CAN2+EpagEq6PzbCXpxP5s62WyzsCJUa4EDvtD7ockNav8YqxkA@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1076.1366944043.3114.python-list@python.org> (permalink) |
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@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-
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll 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