[Numpy-discussion] Count the occurrence of a certain integer in a list of integers

volker lorrmann at physik.uni-wuerzburg.de
Tue Aug 7 08:51:53 EDT 2007


Keith Goodman <kwgoodman <at> gmail.com> writes:

> 
> On 8/7/07, Keith Goodman <kwgoodman <at> gmail.com> wrote:
> > On 8/7/07, Nils Wagner <nwagner <at> iam.uni-stuttgart.de> wrote:
> > > I have a list of integer numbers. The entries can vary between 0 and 19.
> > > How can I count the occurrence of any number. Consider
> > >
> > >  >>> data
> > > [9, 6, 9, 6, 7, 9, 9, 10, 7, 9, 9, 6, 7, 9, 8, 8, 11, 9, 6, 7, 10, 9, 7,
9, 7, 8, 9, 8, 7, 9]
> > >
> > >
> > > Is there a better way than using, e.g.
> > >
> > > >>> shape(where(array(data)==10))[1]
> > > 2
> > >
> > >
> > > to compute the occurrence of 10 in the list which is 2 in this case ?
> >
> > Would list comprehension work?
> >
> > len([z for z in data if z == 10])
> 
> Or is this faster?
> 
> (array(x)==10).sum()
> 

Lets test ;)

In [34]: data = array(data).repeat(1e6)


In [35]: %time shape(where(array(data)==10))[1]
CPU times: user 1.27 s, sys: 0.16 s, total: 1.44 s
Wall time: 1.65


In [36]: %time ([z for z in data if z == 10])
CPU times: user 18.06 s, sys: 0.52 s, total: 18.58 s
Wall time: 18.59




In [37]: %time (array(data)==10).sum()
CPU times: user 0.68 s, sys: 0.20 s, total: 0.88 s
Wall time: 1.36







More information about the NumPy-Discussion mailing list