计算没有元音的字符串长度(Count length of string without vowels)
我有一个字符串: -
a = 'abcderui'我想计算字符串的长度减去元音。 实现这一目标的最佳目标是什么?
目前我在做: -
a = list(a) for i in a: if i in vowels: continue count +=1I've a string:-
a = 'abcderui'I want to count the length of the string a minus the vowels. What would be the fasstest wat to implement that?
Currently I'm doing:-
a = list(a) for i in a: if i in vowels: continue count +=1最满意答案
如果字符串不是很大,那么str.translate是最好的选择:
>>> a = 'abcderui' >>> len(a.translate(None, 'aeiou')) 4时序:
>>> a = 'abcderui'*100 >>> %timeit len(a.translate(None, 'aeiou')) 1000000 loops, best of 3: 1.86 µs per loop >>> %timeit sum(1 for c in a if c not in 'aeiou') 10000 loops, best of 3: 53.2 µs per loop >>> %timeit len(nonvowels.findall(a)) 10000 loops, best of 3: 65.3 µs per loop >>> %timeit len(vowels.sub('', a)) 10000 loops, best of 3: 72 µs per loopIf strings are not huge then str.translate is the best option:
>>> a = 'abcderui' >>> len(a.translate(None, 'aeiou')) 4Timings:
>>> a = 'abcderui'*100 >>> %timeit len(a.translate(None, 'aeiou')) 1000000 loops, best of 3: 1.86 µs per loop >>> %timeit sum(1 for c in a if c not in 'aeiou') 10000 loops, best of 3: 53.2 µs per loop >>> %timeit len(nonvowels.findall(a)) 10000 loops, best of 3: 65.3 µs per loop >>> %timeit len(vowels.sub('', a)) 10000 loops, best of 3: 72 µs per loop更多推荐
发布评论