简体   繁体   中英

How to convert a nested if statement into a lambda function (python)

For a recent Python homework assignment, we were assigned to create a function that would return words in a list that start with 'd'. Here's the relevant code:

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

The above nested if statement that I wrote works when I run the code, which I'm happy about (:D); however, in trying to become more pythonic and astute with the language, I found a very helpful article on why Lambda functions are useful and how to possibly solve this same challenge with a lambda, but I couldn't figure out how to make it work in this case.

I'm asking for guidance on how to potentially write my above nested if statement as a lambda function.

In a way, the lambda equivalent of your if condition would be:

fn = lambda x: x[0] == 'd'  #fn("dog") => True, fn("test") => False

Further, you can use .startswith(..) instead of comparing [0] . It then becomes something like:

letter_list = filter(lambda x: x.startswith('d'), word_list)

But more pythonic is:

letter_list = [x for x in word_list if x.startswith('d')]

I'm not sure what you're asking, because changing the if into a lambda of some sort doesn't seem to be useful. You neglected to post your failed code so we'd know what you want.

However, there is a succinct way to express what you're doing:

def filter_words(word_list, letter):
    return [word in letter_list if word[0] == letter]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM