words = []
while True:
y = input()
if y == "###":
break
words.extend(y.lower().split())
from collections import Counter
Counter(words).most_common(1)
整个代码可以压缩成以下一行:
Counter(y.lower() for x in iter(input, '###') for y in x.split()).most_common(1)
例如。
>>> sys.stdin = StringIO.StringIO("""Here is a line like sparkling wine
Line up now behind the cow
###""")
>>> Counter(y.lower() for x in iter(input, '###') for y in x.split()).most_common(1)
[('line', 2)]
根据要求,没有任何import
s
c = {} # stores counts
for line in iter(input, '###'):
for word in line.lower().split():
c[word] = c.get(word, 0) + 1 # gets count of word or 0 if doesn't exist
print(max(c, key=c.get)) # gets max key of c, based on val (count)
为了不必再次通过字典来查找最大单词,请在进行过程中跟踪它:
c = {} # stores counts
max_word = None
for line in iter(input, '###'):
for word in line.lower().split():
c[word] = c.get(word, 0) + 1 # gets count of word or 0 if doesn't exist
if max_word is None:
max_word = word
else:
max_word = max(max_word, word, key=c.get) # max based on count
print(max_word)