Colly
Colly

Reputation: 41

Combining multiple count items in python?

return function.count('1') + given.count('2') + given.count('3')

is there any way I can simplify this line? also i've tried return function.count('1', '2', '3') but runs an error the goal is to count all numbers contained in the string lol

Upvotes: 0

Views: 6899

Answers (3)

Daniel Hao
Daniel Hao

Reputation: 4981

Would this be sufficiently faster?

count = Counter(strings) 
sum(v for k, v in count.items() if k in "0123456789")

Upvotes: 0

unutbu
unutbu

Reputation: 881037

Assuming function is the same as given,

sum(function.count(x) for x in '1 2 3'.split())

The variable name function (and given) is somewhat confusing since the question also says

the goal is to count all numbers contained in the string.

So if function is a string and you wish to extend the count to all digits you could use

import string
sum(function.count(x) for x in string.digits)

This suffices if function is a short string. But note that each call to count requires a full pass through the string function. If function is a very large string, doing 10 passes may be inefficient.

In that case, it may be better to discard characters that are not digits in one pass:

def onepass(x):
    return sum(1 for c in x if c in string.digits)

Or, you could remove all the non-digits from the string (using the translate method) and then use len. For example:

def drop_nondigits(x):
    # The essential idea comes from the translator recipe in Python Cookbook;
    # It can also be found here
    # http://code.activestate.com/recipes/303342-simple-wrapper-for-stringtranslate/
    keep = string.digits
    allchars = string.maketrans('', '')
    delete = allchars.translate(allchars, keep)
    return len(x.translate(allchars, delete))    

And out of curiosity, let's compare it to using collections.Counter:

import collections
def using_counter(x):
    counter = collections.Counter(x)
    return sum(counter[d] for d in string.digits)

It turns out that drop_nondigits is fastest:

In [26]: x = 'some very large string 123456' * 1000

In [38]: %timeit using_counter(x)
100 loops, best of 3: 7.26 ms per loop

In [29]: %timeit onepass(x)
100 loops, best of 3: 2.52 ms per loop

In [32]: %timeit drop_nondigits(x)
10000 loops, best of 3: 34.9 us per loop

Upvotes: 3

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251196

use Counter() to count all numbers contained in the string:

>>> from collections import Counter
>>> count= Counter("abcd12341134..09--01abc")
>>> [x for x in count.items() if x[0] in "0123456789"]
[('1', 4), ('0', 2), ('3', 2), ('2', 1), ('4', 2), ('9', 1)]

or using Counter() with filter():

>>> strs="abcd12341134..09--01abc"
>>> Counter(filter(lambda x:x in "0123456789",strs))
Counter({'1': 4, '0': 2, '3': 2, '4': 2, '2': 1, '9': 1})

Upvotes: 2

Related Questions