Get the App
SLTechnology News&Howtos  ›  Development  › 

How python uses Lambda and Map functions

Shulou Source: shulou.com Published: 2022-06-01 04:26:17 09月12日 Update

Lambda and Map

Generally speaking, Lambda functions are relatively small, and it does not need to define a function name. So why do you need anonymous functions? To put it simply, Lambda most often performs some intuitive operations, it does not require a standard function definition, and it does not require a new function name to be called again.

Let's take the above square and then add 5 as an example. We defined a standard function, def stupid_func (x), and now we can try the Lambda anonymous function:

> stupid_func = (lambda x: X * * 2 + 5) > print ([stupid_func (1), stupid_func (3), stupid_func (5)]) [6,14,30]

So why do we use the above expression? A large part of the reason is that when we want to perform some simple operations, we can do it without defining a real function. For example, sorting list elements is an intuitive way to use the sorted () method:

> my_list = [2, 1, 0,-1,-2] > > print (sorted (my_list)) [- 2,-1, 0, 1, 2]

This can only be sorted from big to small or from small to big by default, but with the help of Lambda expressions, we can achieve freer sorting criteria.

> > print (sorted (my_list, key = lambda x: X * * 2)) [0,-1, 1,-2, 2]

Map is a simple function that applies a function to other sequence elements, such as lists. If we have two lists and we want to multiply the corresponding elements of the two lists, we can do this quickly using the lambda function and map:

> print (list (map (lambda x, y: X * y, [1,2,3], [4,5,6])) [4,10,18]

The above code is very elegant, and if you don't use both of them, the general expression needs to be written like this:

> x, y = [1,2,3], [4,5,6] > > z = [] > for i in range (len (x)): > z.append (x [I] * y [I]) > > print (z) [4,10,18] these are all the contents of this article "how python uses Lambda and Map functions". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Functions sorting intuition elements methods standards articles facets two content expressions operations powerful large minimum elegant free from small to big generally speaking not Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Redmi Xiaomi OPPO Reno Apple