Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #44374
| References | <bfc57a5f-bbcb-46a4-b59a-e7fa55527da1@y12g2000yqb.googlegroups.com> <klce8o$2pp$4@dont-email.me> |
|---|---|
| Date | 2013-04-25 19:16 -0600 |
| Subject | Re: Pythonic way to count sequences |
| From | Modulok <modulok@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1074.1366938979.3114.python-list@python.org> (permalink) |
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 | Next 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