Special Python syntax

Source: Internet
Author: User
Python has built-in special functions that are very python-like. This makes the code more concise. Example: 1 filter (function, sequence): str [& amp; 39; a & amp; amp; Python has built-in special functions that are very python-specific. This makes the code more concise.

For example:

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']

Execute function (item) in sequence for items in sequence, and combine items with the execution result of True into a List/String/Tuple (depending on the sequence type) to return.

It can be viewed 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

# Using 'a.txt ',' B .txt ', 'c.txt', 'd.txt ']

Execute function (item) in sequence for items in sequence. see the execution result to form a List and 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 (10), 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, 1,100), 20)

#4950 (note: 1 + 2 +... + 99)

#4970 (note: 1 + 2 +... + 99 + 20)

Call the function sequentially for items in sequence. if starting_value exists, it can also be called as an initial value. for example, it can be used to sum the List:

4 lambda:

G = lambda s: s + ". follicle"

Print g ("haha ")

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

# Haha. HCG

#6

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

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.