return function.count('1') + given.count('2') + given.count('3')
この行を単純化する方法はありますか? また、 return function.count('1', '2', '3') を試しましたが、エラーが発生しました。目標は、文字列に含まれるすべての数値をカウントすることです笑
return function.count('1') + given.count('2') + given.count('3')
この行を単純化する方法はありますか? また、 return function.count('1', '2', '3') を試しましたが、エラーが発生しました。目標は、文字列に含まれるすべての数値をカウントすることです笑
function
が と同じであると仮定するとgiven
、
sum(function.count(x) for x in '1 2 3'.split())
変数名function
(およびgiven
)は、質問にもあるため、やや混乱しています
目標は、文字列に含まれるすべての数値をカウントすることです。
したがってfunction
、文字列であり、使用できるすべての桁にカウントを拡張したい場合
import string
sum(function.count(x) for x in string.digits)
function
が短い文字列の場合はこれで十分です。ただし、 への各呼び出しでcount
は、 string を完全に通過する必要があることに注意してくださいfunction
。function
が非常に大きな文字列の場合、10 回のパスを行うのは非効率的です。
その場合、 1 回のパスで数字ではない文字を破棄する方がよい場合があります。
def onepass(x):
return sum(1 for c in x if c in string.digits)
または、( translate メソッドを使用して)文字列からすべての非数字を削除してから、 を使用することもできますlen
。例えば:
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))
好奇心から、 collections.Counterの使用と比較してみましょう:
import collections
def using_counter(x):
counter = collections.Counter(x)
return sum(counter[d] for d in string.digits)
それdrop_nondigits
が最速であることがわかります:
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
Counter()
文字列に含まれるすべての数値をカウントするために使用します。
>>> 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)]
またはCounter()
で使用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})