Some special uses of Python Python (map, reduce, filter, lambda, list derivation, etc.) __python

Source: Internet
Author: User
map function:

Prototype: Map (function, sequence), which is to map a list to another list,

How to use:

def f (x):

Return x**2

L = Range (1,10)

Map (f,l)

OUT[3]: [1, 4, 9, +, BA] reduce function

Prototypes: Reduce (function, sequence, startvalue), which is to generalize a list into one output,
How to use:

def f2 (x,y):

Return X+y

Reduce (f1,l)

OUT[7]: 45

Reduce (f2,l,10)

OUT[8]: The filter function

Prototype: filter (function, sequence) that filters out some elements of a list according to the function defined.
How to use:

def f2 (x):

return x%2!= 0

Filter (F2,L)

OUT[5]: [1, 3, 5, 7, 9]

Remember: The function here must return a Boolean value. Lambda functions

Prototypes: Lambda < parameters: function body, implicit function, define some simple operations,
How to use:

F3 = Lambda x:x**2

F3 (2)

OUT[10]: 4

You can also combine map, reduce, and filter to use, such as:

Map (f3,l)

OUT[11]: [1, 4, 9, +, BA] list of deduced

Basic form: [X for item in sequence <if (conditions)], where x represents the operation of the item,

How to use:

[I**2 for I in L]

OUT[12]: [1, 4, 9, +, BA] dictionary set default values

The default value of setting entries in the Python dictionary is sometimes useful, such as initializing a dictionary.
How to use:

x = {}

X.setdefault (1,0)

OUT[15]: 0

X[2] = 10

X

OUT[17]: {1:0, 2:10}

X.setdefault (2,1)

OUT[18]: 10


Author: Alex Yu
Source: http://www.cnblogs.com/biaoyu/
The copyright of this article is owned by the author and blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to give the original connection, Otherwise, the right to pursue legal liability is retained.

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.