对于最近的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函数的指导.
在某种程度上,你的if条件的lambda等价物是:
fn = lambda x: x[0] == 'd' #fn("dog") => True, fn("test") => False
Run Code Online (Sandbox Code Playgroud)
此外,您可以使用.startswith(..)而不是比较[0].它变成了类似的东西:
letter_list = filter(lambda x: x.startswith('d'), word_list)
Run Code Online (Sandbox Code Playgroud)
但更多的pythonic是:
letter_list = [x for x in word_list if x.startswith('d')]
Run Code Online (Sandbox Code Playgroud)