d78*_*89w 1 python list-comprehension sum function list
我有一个需要列表理解的问题并且必须使用sum()函数,它可能不是最好的方法,但这就是要求的.请阅读以下问题:
问题: 编写一个使用列表推导的函数word_count(字符串,单词)和sum()函数来计算单词在字符串中出现的次数.将此应用于狄更斯弦.提示:sum()函数可用于添加列表的元素.例如,sum([1,2,3])将返回6.某些单词是否有问题?哪些是为什么?尝试使用条带字符串方法(我们稍后在讨论正则表达式时再次访问它).
使用字符串:
dickens = """
It was the best of times, it was the worst of times,
it was the age of wisdom, it was the age of foolishness, it was the epoch of belief,
it was the epoch of incredulity, it was the season of Light, it was the season of Darkness,
it was the spring of hope, it was the winter of despair, we had everything before us, we had
nothing before us, we were all going direct to Heaven, we were all going direct the other way -
in short, the period was so far like the present period, that some of its noisiest authorities
insisted on its being received, for good or for evil, in the superlative degree of comparison only.
"""
def word_count(s, w):
return [word for word in s.strip().split() if w == word ]
print(word_count(dickens, "it"))
output= ['it', 'it', 'it', 'it', 'it', 'it', 'it', 'it', 'it']
Run Code Online (Sandbox Code Playgroud)
所以基本上从这里开始,使用sum函数,我如何得到将所有元素求和为9的答案.
def word_count(s, w):
return sum([word for word in s.strip().split() if w == word ])
print(word_count(dickens, "it"))
Run Code Online (Sandbox Code Playgroud)
这对我不起作用,但必须看起来像这样.
谢谢
如果必须sum()用于计数目的,请尝试将单词的每个出现处理为1.尽管这是一个次优的解决方案,但它可能正好在给定的要求下.
sum([1 for word in s.strip().split() if w == word ])
^
Run Code Online (Sandbox Code Playgroud)
它相当于:
sum([1, 1, 1, 1, ......])
Run Code Online (Sandbox Code Playgroud)
还有其他形式(基本上相同)的解决方案:
sum(w == word for word in s.strip().split())
Run Code Online (Sandbox Code Playgroud)
它被解释为
sum( (w == word) for word in s.strip().split() )
Run Code Online (Sandbox Code Playgroud)
和布尔值在添加时被视为1和0,因此您可以获得匹配单词的数量.
后一种方法比第一种方法更快,因为它创建了一个生成器对象,而不是一个充满1的真实列表.