Python function lambda (), filter (), map (), reduce ()

Source: Internet
Author: User

(1) Lambda

A lambda is a python that creates an anonymous function in the form of the following syntax:

Lambda [arg1[, arg2, ... argn]]: expression
Use examples:

#使用法一
fun = lambda x,y:x+y
print Fun (1,2)
#输出结果为:
3

#使用法二
print (lambda x,y:x+y) (1,2)
# Output:
3

#上面法一和法二相当于:
def func_1 (x, y): return
	x + y
print func_1 (1, 2)

(2) Map ()

Map (function, sequence): Performs a function (item) on the item in sequence, as the execution result consists of a list return. Examples are as follows:

def cube (x): Return
        x*x*x
print map (cube, range (1))
#输出结果为:
[1, 8, 27, 64, 125, 216, 343, 512, 729 , 1000]


(3) Reduce ()

Reduce (function, sequence, starting_value): Iterates the call function on the item order in sequence, and if there is a starting_value, it can also be invoked as an initial value. For example, you can use to sum the list:

def add (x,y): return
	x + y
print reduce (add, range (1))  
print reduce (add, range (1),

#输出结果为: 
  55 #1 +2+3+4+5+6+7+8+9+10
#1 +2+3+4+5+6+7+8+9+10+20

(4) filter ()
Filter (function, sequence): Performs a function (item) on the item in sequence, and makes an item that executes the result to true list/string/ Tuple (depending on the type of sequence) is returned. Examples are as follows
#例1
def f (x): Return
	x 2!= 0 and x 3!= 0 
print filter (f, Range (2)) 
#输出结果为:
[5, 7, 11, 13, 1 7,

#例2]
def f (x): Return
	x!= ' A ' 
print filter (F, "abcdef") 
#输出结果为:
' bcdef '


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.