python - 在 python 中使用函数 sum() 和列表理解

标签 python list function sum list-comprehension

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

问题: 编写一个函数 word_count(string, word),它使用列表理解和 sum() 函数来计算单词在字符串中出现的次数。将此应用于狄更斯字符串。提示:sum() 函数可用于添加列表的元素。例如, 总和 ([1, 2, 3]) 会返回 6. 某些词有问题吗?哪些以及为什么?尝试使用 strip string 方法(我们将在稍后讨论正则表达式时重新讨论它)。

使用的字符串:

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']

所以基本上从这里开始,使用 sum 函数,我怎样才能得到将所有元素相加为 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() )

和 bool 值在添加时被视为 1 和 0,因此您可以获得匹配单词的数量。

后一种方法比第一种方法更快,因为它创建了一个生成器对象而不是一个真正的全 1 列表。

关于python - 在 python 中使用函数 sum() 和列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49503617/

相关文章:

python - ModuleNotFoundError : No moudle name <name> in docker python

python - 如何发送带有表情符号输出的 Twilio 短信回复

python - 如果语句检查列表包含在不应该返回 true 时返回 true

Python:有没有办法在列表中指定的数据帧的所有列上单独应用函数? Pyfinance 包

c - 在 C 中的函数中使用#define 数字

python - 让 python 工作,内部服务器错误

python - python pandas dataframe 列中的电子邮件验证

list - F# 是否有等同于 Haskell 的方法?

java - 将对象的 int 变量与 String 进行比较

c++ - 我可以在 C++ 的模板函数体中使用模板变量吗