这是我当前的解决方案,除了我不确定如果两个或多个单词绑定,代码会做什么,我还需要处理它。
def most_repeating_vowel(word):
vowels = {"a":0,"e":0,"i":0,"o":0,"u":0}
for i in word:
if i in vowels:
vowels[i]+=1
return max(vowels.values())
def most_repeating_word(seq):
return max(seq, key=most_repeating_vowel)
mylist = ["giraffe","elephant","ox","yyyyyyy","iiiii"]
most_repeating_word(mylist)
有没有更python的方法可以处理这个问题?
我喜欢使用str.count
:
max(mylist, key=lambda w: max(map(w.count, 'aeiou')))
使用示例数据进行基准测试:
Round 1 Round 2 Round 3
16.1 us 16.0 us 15.5 us Stef
5.2 us 5.0 us 5.1 us KellyBundy
对于较长的单词(每个单词乘以 1000):
Round 1 Round 2 Round 3
1466 us 1476 us 1480 us Stef
71 us 71 us 71 us KellyBundy
基准代码(在线试用!
from timeit import timeit
import collections
def Stef(mylist):
def count_most_repeated_vowel(w):
c = collections.Counter(w)
return max(c[v] for v in 'aeiou')
return max(mylist, key=count_most_repeated_vowel)
def KellyBundy(mylist):
return max(mylist, key=lambda w: max(map(w.count, 'aeiou')))
funcs = Stef, KellyBundy
def benchmark(mylist, number, label, format):
tss = [[] for _ in funcs]
for r in range(1, 4):
print(*(label % i for i in range(1, r+1)))
for func, ts in zip(funcs, tss):
t = timeit(lambda: func(mylist), number=number) / number
ts.append(t)
print(*(map(format, ts)), func.__name__)
print()
mylist = ["giraffe","elephant","ox","yyyyyyy","iiiii"]
benchmark(mylist, 50000, 'Round %d ', lambda t: '%4.1f us ' % (t * 1e6))
benchmark([w * 1000 for w in mylist], 500, 'Round %d ', lambda t: '%4d us ' % (t * 1e6))
使用collections.Counter
的解决方案,它是用于计算事物的dict
子类:
import collections
mylist = ["giraffe","elephant","ox","yyyyyyy","iiiii"]
def count_most_repeated_vowel(w):
c = collections.Counter(w)
return max(c[v] for v in 'aeiou')
print(max(mylist, key=count_most_repeated_vowel))
# 'iiiii'
- 有关
collections.Counter
的文档