使用python中的列表理解的函数sum()



我有一个需要列表理解的问题,必须使用 sum> sum((函数,这可能不是最好的方法但这就是问的。请阅读下面的问题:

问题:编写一个函数word_count(字符串,word(,该函数使用列表理解和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']

基本上从这里,使用总和函数,我如何获得答案以将所有元素汇总为9。

def word_count(s, w):
   return sum([word for word in s.strip().split() if w == word ])
print(word_count(dickens, "it"))

这对我不起作用,但必须看起来像这样。

谢谢

如果您必须使用 sum()进行计数目的,请尝试将单词的每一个出现视为1。尽管这是一个次优的解决方案,但它可能是在给定要求下的。

sum([1 for word in s.strip().split() if w == word ])
     ^

它等效于:

sum([1, 1, 1, 1, ......])

还有其他形式的(本质上是相同的(解决方案:

sum(w == word for word in s.strip().split())

它被解释为

sum( (w == word) for word in s.strip().split() )

和布尔值在添加时被视为一个和零,因此您会得到匹配单词的数量。

后者的方法比第一个方法快,因为它创建了一个生成器对象,而不是一个完整的1个。

如果存在,只需在数组中添加1个:

def word_count(s, w):
   return sum(1 for word in s.strip().split() if w == word)

这是他不能使用len的问题,他必须使用总和。

其他像阿德里亚诺(Adriano(这样的其他人给出了很好的答案。

如果您想完成的工作是计算" IT"的出现,则可以将count(substr)功能用于字符串。

在您的情况下,

print(dickens.lower().count('it')) # prints 13

编辑:添加lower(),谢谢ColdSpeed!

使用列表理解的长度。

def word_count(s, w):
    return sum([1 for word in s.strip().split() if w == word ])
print(word_count(dickens, "it"))

最新更新