Python: Lambda function to count specific letters in a word and then iterate through a list of words
Question:
I am trying to convert a list comprehension logic to a lambda function. The problem I face is that the function is returning the first value and not iterating through the list.
In this example, I need to return words that contain the max A’s (lower or upper). Here is how I have tried so far
sample list of items -- notice 'armchair' has the max a's
items = ['pillow', 'armchair', 'aloegel', 'hammer']
Wrote a general function (maxa) to return a max item based on count. Note that ‘tally’ is another function I’ve written which works perfectly. ‘Tally’ just returns a count based on certain conditions.
def maxa(tally, items):
mylist = [(tally(word), word) for word in items]
return max(mylist, key = lambda x : x[0])[1]
I am now trying to replace the function ‘tally’ with a lambda function. This is what I have written so far and returns just the first word in the list. This returns ‘pillow’ instead of ‘amrchair’ so I assume this is somehow not looping. What am I missing?
maxa(lambda x : sum(letter in ('a', 'A') for letter in word), items)
Answers:
Just updating the question with @Barmar ‘s answer (which worked perfectly)
maxa(lambda x : sum(letter in (‘a’, ‘A’) for letter in x), items)
I am trying to convert a list comprehension logic to a lambda function. The problem I face is that the function is returning the first value and not iterating through the list.
In this example, I need to return words that contain the max A’s (lower or upper). Here is how I have tried so far
sample list of items -- notice 'armchair' has the max a's
items = ['pillow', 'armchair', 'aloegel', 'hammer']
Wrote a general function (maxa) to return a max item based on count. Note that ‘tally’ is another function I’ve written which works perfectly. ‘Tally’ just returns a count based on certain conditions.
def maxa(tally, items):
mylist = [(tally(word), word) for word in items]
return max(mylist, key = lambda x : x[0])[1]
I am now trying to replace the function ‘tally’ with a lambda function. This is what I have written so far and returns just the first word in the list. This returns ‘pillow’ instead of ‘amrchair’ so I assume this is somehow not looping. What am I missing?
maxa(lambda x : sum(letter in ('a', 'A') for letter in word), items)
Just updating the question with @Barmar ‘s answer (which worked perfectly)
maxa(lambda x : sum(letter in (‘a’, ‘A’) for letter in x), items)