Python Special Syntax: filter, map, reduce, lambda

Source: Internet
Author: User

Python has built-in special functions that are Python-specific. You can make your code more concise.

Examples can be seen:

1 filter (function, sequence):

str = [' A ', ' B ', ' C ', ' d ']

def fun1 (s): return s if s! = ' a ' else None

RET = filter (FUN1, str)

Print ret

# # [' B ', ' C ', ' d ']

A function (item) is executed on item in sequence, and the item that executes the result of true consists of a list/string/tuple (depending on the type of sequence) returned.

Can be seen as a filter function.

2 map (function, sequence)

str = [' A ', ' B ', ' C ', ' d ']

def fun2 (s): return S + ". txt"

ret = map (fun2, str)

Print ret

# # [' A.txt ', ' b.txt ', ' c.txt ', ' d.txt ']

Execute function (item) on item in sequence, and see the result of the execution to make a list return:

Map also supports multiple sequence, which requires that the function also supports the corresponding number of parameter inputs:
def add (x, y): Return x+y
Print map (add, Range), range (10))
##[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]


3 reduce (function, sequence, Starting_value): def add1 (x, y): return x + y

Print reduce (ADD1, range (1, 100))

Print reduce (ADD1, range (1, 100), 20)

# 4950 (Note: 1+2+...+99)
# 4970 (Note: 1+2+...+99+20)

The function is called on an iteration of the item order in sequence, and if there is starting_value, it can also be called as an initial value, for example to sum the list:


4 Lambda:

g = lambda s:s + ". FSH"

Print g ("haha")

Print (Lambda x:x * 2) (3)

# # HAHA.FSH

# 6

This is an interesting syntax that Python supports, which allows you to quickly define the smallest function of a single line, similar to a macro in C, which are called lambda functions.

Python Special Syntax: filter, map, reduce, lambda

Related Article

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.