对于最近的Python作业分配,我们被指派创建一个函数,该函数将返回以'd'开头的列表中的单词.这是相关的代码:
def filter_words(word_list, letter):
'''
INPUT: list of words, string
OUTPUT: list of words
Return the words from word_list which start with the given letter.
Example:
>>> filter_words(["salumeria", "dandelion", "yamo", "doc loi", "rosamunde",
"beretta", "ike's", "delfina"], "d")
['dandelion', 'doc loi', 'delfina']
'''
letter_list = []
for word in word_list:
if word[0] == letter:
letter_list.append(word)
return letter_list
Run Code Online (Sandbox Code Playgroud)
我编写的上述嵌套if语句在我运行代码时起作用,我很高兴(:D); 然而,在尝试使用该语言变得更加pythonic和精明,我发现了一篇非常有用的文章,关于为什么Lambda函数是有用的以及如何用lambda解决同样的挑战,但我无法弄清楚如何使它工作在这种情况下.
我正在寻求有关如何将我的上述嵌套if语句写为lambda函数的指导.