我有一个大约一百个单词的列表和一个包含八个字母的列表,我如何搜索每个字母以及单词,找出列表中字母最多的单词,然后打印该单词。
问问题
81 次
2 回答
1
def searchWord(letters, word):
count = 0
for l in letters:
count += word.count(l)
return count
words = ['hello', 'world'];
letters = ['l', 'o']
currentWord = None
currentCount = 0
for w in words:
n = searchWord(letters, w)
print "word:\t", w, " count:\t", n
if n > currentCount:
currentWord = w
currentCount = n
print "highest word count:", currentWord
于 2012-11-27T16:22:07.497 回答
0
效率不高,但你可以这样做:
def search(test, words):
return sorted(((sum(1 for c in word if c in test), word) for word in words),
reverse=True)
这会给你一个排序的单词和计数列表。
于 2012-11-27T16:14:59.153 回答