gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:30:11 24 4
gpt4 key购买 nike

我有一个问题需要列表理解,并且必须使用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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com