When and Why to Map a Lambda function to a List

前端 未结 1 1771
遥遥无期
遥遥无期 2020-12-22 00:48

I am working through a preparatory course for a Data Science bootcamp and it goes over the Lambda keyword, Map and Filter functions fa

相关标签:
1条回答
  • 2020-12-22 01:34

    Personally, a map of a lambda makes me gag. Just use a generator expression! And a list of a map of a lambda is even worse cause it could be a list comprehension!

    def error_line_traces(x_values, y_values, m, b):
        return [error_line_trace(x_values, y_values, m, b, x) for x in x_values]
    

    Look how much shorter and clearer that is!

    A filter of a lambda can also be rewritten as a comprehension. For example:

    list(filter(lambda x: x>5, range(10)))
    [x for x in range(10) if x>5]
    

    That said, there are good uses for lambda, map, and filter, but usually not in combination. Even list(map(...)) can be OK depending on the context, for example converting a list of strings to a list of integers:

    [int(x) for x in list_of_strings]
    list(map(int, list_of_strings))
    

    These are about as clear and concise, so really the only thing to consider is whether people reading your code will be familiar with map.

    Once you get past the bootcamp, keep in mind that map and filter are iterators and do lazy evaluation, so if you're only looping over them and not building a list, they're actually preferable for performance reasons, though a generator performs just as well.


    BTW, minor correction: lambda is a keyword, not a function.

    0 讨论(0)
提交回复
热议问题