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


Groups > comp.lang.python > #44334

Re: Pythonic way to count sequences

From Serhiy Storchaka <storchaka@gmail.com>
Subject Re: Pythonic way to count sequences
Date 2013-04-25 15:36 +0300
References <bfc57a5f-bbcb-46a4-b59a-e7fa55527da1@y12g2000yqb.googlegroups.com> <CAPTjJmp9T0osVkCremEaEFz78SiyO+f34ND3_jU1_hcCOb_w1w@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.1057.1366893429.3114.python-list@python.org> (permalink)

Show all headers | View raw


25.04.13 08:26, Chris Angelico написав(ла):
> 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

Or alternatives:

count = {}
for sequence_tuple in list_of_tuples:
      if sequence_tuple] in count:
           count[sequence_tuple] += 1
      else:
           count[sequence_tuple] = 1

count = {}
for sequence_tuple in list_of_tuples:
      try:
           count[sequence_tuple] += 1
      except KeyError:
           count[sequence_tuple] = 1

import collections
count = collections.defaultdict(int)
for sequence_tuple in list_of_tuples:
      count[sequence_tuple] += 1

But of course collections.Counter is a preferable way now.

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