簡體   English   中英

使用功能sum()與python中的列表理解

[英]using the function sum() with a list comprehension in python

我有一個需要列表理解的問題, 必須使用sum()函數,它可能不是最好的方法,但這就是要問的問題。 請閱讀以下問題:

問題:編寫一個函數word_count(string,word),該函數使用列表推導和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']

所以基本上從這里開始,使用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() )

和布爾值在添加時被視為1和0,因此您可以獲得匹配的單詞數。

后一種方法比第一種更快,因為它創建了一個生成器對象,而不是一個全為1的真實列表。

只需將1添加到數組(如果存在):

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

關於這個問題,他不能使用len ,必須使用sum,這很明確。

像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"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM