如果它必须非常快,我会写一个c extension。
仅使用 python,有很多方法可以做到这一点。您可以测试一些,看看哪个是最快的。因为python的内置函数已经过优化,所以我会尽可能多地使用它们而不是循环,所以我就是这样做的:
def commonLetter(words):
joined = ''.join(words) # creating one string from all the words
letterDict = {} # will contain the number of occurences for each letter
def addToDict(letter):
try: letterDict[letter] += 1
except: letterDict[letter] = 1
map(addToDict, joined) # applying addToDict to all the letters
return max(letterDict.keys(), key=lambda letter: letterDict[letter])
words = [
'Python', 'what', 'is', 'the',
'fastest', 'way', 'to', 'find',
'the', 'most', 'common', 'letter',
'in', 'a', 'list', 'of', 'words'
]
print commonLetter(words) # outputs 't'
你也可以试试:
def commonLetter(words):
joined = ''.join(words) # creating one string from all the words
tuples = map(lambda letter: (letter, joined.count(letter)), set(joined))
return max(tuples, key=lambda tup: tup[1])[0]
或者:
def commonLetter(words):
joined = ''.join(words) # creating one string from all the words
return Counter(joined).most_common(1)[0][0]