Python's lambda,filter,map,reduce function

Source: Internet
Author: User

g = Lambda x:x+1

Take a look at the results of the execution:

G (1)

>>>2

G (2)

>>>3

Of course, you can also use this:

Lambda x:x+1 (1)

>>>2

It can be thought that lambda, as an expression, defines an anonymous function, the code x for the example above is the entry parameter, x+1 is the function body, and is represented by a function:

def g (x):
Return x+1

Very easy to understand, where Lambda simplifies the writing of function definitions. Code is more concise, but the use of functions is more intuitive and easy to understand.

In Python, there are also several well-defined global functions that are easy to use, filter, map, reduce

filter () function
The filter () function consists of two parameters, function and list, respectively. The function filters the items in the list parameter based on whether the result returned by a function parameter is true, and finally returns a new list, as shown in the following example:
>>>a=[1,2,3,4,5,6,7]
>>>b=filter (Lambda x:x>5, a)
>>>print b
>>>[6,7]
If the value of the filter parameter is none, the identity () function is used and all false elements in the list parameter are deleted. As shown below:
>>>a=[0,1,2,3,4,5,6,7]
B=filter (None, a)
>>>print b
>>>[1,2,3,4,5,6,7]

From Functools import reduce

>>> foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
>>>
>>> Print (list (filter (lambda x:x% 3 = = 0, foo))
[18, 9, 24, 12, 27]
>>>
>>> Print (list (map (lambda x:x * 2 + ten, foo))
[14, 46, 28, 54, 44, 58, 26, 34, 64]
>>>
>>> print (Reduce (lambda x, y:x + y, foo))
139

The role of the map in the example above is very simple and clear. But does Python have to use lambda to make this simple? In the object traversal process, in fact Python for. In.. The IF syntax is already strong and is more readable than lambda.

For example, the map above can be written as:

print [x * 2 + ten for x in Foo]

It's very concise and easy to understand.

The filter example can be written as:

print [x for x in foo if x% 3 = = 0]

It's also easier to understand than a lambda way.

Here's a brief description of what Lambda is, and here's why you use lambda to see an example (from apihelper.py):

Processfunc = Collapse and (lambda s: "". Join (S.split ())) or (lambda s:s)

  In Visual Basic, you are most likely to create a function that takes a string argument and a collapse parameter, and uses the if statement to determine whether to compress the white space before returning the corresponding value. This approach is inefficient because the function may need to handle every possible situation. Every time you call it, it will have to decide if you want to compress the blanks before giving them what you want. In Python, you can take the decision logic out of the function and define a cut-off Lambda function to provide the exact (unique) you want. This approach is more efficient, more elegant, and rarely leads to bugs that are annoying (oh, think those parameters are dizzy).

Using this example, we found that the use of lambda is a lot easier to simplify the code and make the code concise and clear. However, it is important to note that this reduces the readability of the code to some extent. People who are not very familiar with Python may find this incomprehensible.

Lambda defines an anonymous function

Lambda does not increase the efficiency of the program, only makes the code more concise.

If you can use for...in ... If to complete, be resolute without lambda.

If you do not include loops within LAMBDA,LAMBDA, if so, I would rather define functions to do so that the code is reusable and better readable.

Summary: Lambda exists to reduce the definition of a single-line function.


 ·map () function
Two parameters of map () one is the function name and the other is a list or tuple.
>>>map (Lambda x:x+3, a) #这里的a同上
>>>[3,4,5,6,7,8,9,10]

#另一个例子
>>>a=[1,2,3]
>>>b=[4,5,6]
>>>map (Lambda X,y:x+y, A, b)
>>>[5,7,9]

#下面这个模块以一个现有的文本为参数, clear the extra spaces, and then convert all the text to uppercase (English). For the child demo program to create a string that map.txt the file with extra spaces before and after a few lines. Note: You can only remove the extra space before and after.
From string import Strip,upper
#functions:
#
def map_add (x):
Return x+3
#
If __name__== ' __map_add__ ':
Map_add (x)
#zip file
Def zip_file ():
#open file
f = open (' Map.txt ')
lines = F.readlines ()
Print lines
F.close ()
#
print ' before/n '
For Eachline in lines:
print ' [%s] '% eachline[:-1]
#
print ' after/n '
For Eachline in map (upper, map (strip, lines)):
print ' [%s] '% eachline
#
If __name__== ' __zip_file__ ':
Zip_file ()

·reduce () function
The reduce function reduces the sequence of input parameters to a single value in a given way, by first removing the first two elements from the sequence and passing it to the two-tuple function, finding a value, and then looping the next value into the sequence until the last value.
>>>reduce (Lambda x,y:x*y, [1,2,3,4,5]) # (((1*2))
>>>120

>>>reduce (Lambda x,y:x*y, [i], 10)
>>>60 # (1*2) *10

Python's lambda,filter,map,reduce function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.