Home > Software design >  How can I turn this function into Lambda?
How can I turn this function into Lambda?

Time:03-03

I'm trying to turn this function into a one line function for assignment purposes.

def counter(list_to_count, char_to_count):
    ocurrences_list = []
    for i in list_to_count:
        x = i.count(char_to_count)
        ocurrences_list.append(x)
    return ocurrences_list

This function takes a list of strings and counts the ocurrences of "char" in each element, then makes a list with the amount of ocurrences of "char" per element.

CodePudding user response:

Use a list comprehension:

lambda list_to_count, char_to_count: [i.count(char_to_count) for i in list_to_count]

CodePudding user response:

You can simply use a list comprehension to achieve your goal, but if you really want to turn it into a lambda function, just use:

f = lambda list_to_count, char_to_count: [elem.count(char_to_count) for elem in list_to_count]
  • Related