我推荐这个:
map(lambda word: word.lower(), paragraph.split()).count("the")
输出:
>>> paragraph = "This is a day of national consecration. And I am certain that on this day my fellow Americans expect that on my induction into the Presidency, I will address them with a can
dor and a decision which the present situation of our people impels. This is preeminently the time to speak the truth, the whole truth, frankly and boldly. Nor need we shrink from honestly f
acing conditions in our country today. This great Nation will endure, as it has endured, will revive and will prosper. So, first of all, let me assert my firm belief that the only thing we h
ave to fear is fear itself, nameless, unreasoning, unjustified terror which paralyzes needed efforts to convert retreat into advance. In every dark hour of our national life, a leadership of
frankness and of vigor has met with that understanding and support of the people themselves which is essential to victory. And I am convinced that you will again give that support to leader
ship in these critical days."
>>> map(lambda word: word.lower(), paragraph.split()).count("the")
7
由于我的解决方案可能看起来很奇怪,这里从左到右稍微解释一下:
map(function, target)
:这会将函数应用于 的所有元素target
,因此target
必须是列表或其他一些可迭代的。在这种情况下,我们正在映射一个lambda
函数,这可能有点吓人,所以请阅读下面的内容
.lower()
:在这种情况下,采用其应用的任何字符串的小写word
字母。这样做是为了确保“the”、“The”、“THE”、“TheE”等都被计算在内
.split()
: 这会将字符串 ( paragraph
) 通过括号中提供的分隔符拆分为列表。在没有分隔符的情况下(例如这个),一个空格被假定为分隔符。请注意,当分隔符被忽略时,顺序分隔符会被合并。
.count(item)
item
:这会计算其应用到的列表中的实例。请注意,这不是计算事物的最有效方法(如果您关心速度,则必须使用正则表达式)
可怕的 lambda 函数:
lambda 函数不容易解释或理解。我花了很长时间才了解它们是什么以及它们何时有用。 我发现本教程很有帮助。
我对 tl;dr 的最佳尝试是 lambda 函数是小型匿名函数,可以方便地使用。我知道这充其量是不完整的,但我认为它应该足以满足这个问题的范围