Many languages provide a mechanism for handling parameters or variables, as flexible Python provides some special methods for function processing
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
map (function, sequence): performs a function (item) on the item in sequence, see the Execution results form a list
reduce (function, sequence, starting_value): iterate Call function on item order in sequence
sum (sequence): accumulates elements in a collection
Here's a simple little example of the above description:
Copy Code code as follows:
__author__ = ' Administrator '
From Functools import reduce
#主要用来掩饰map可以将某个序列中的元素传递给某个特殊的函数来处理
Def Map_demo ():
#定义一个将字母转换成大写的函数
def to_upper (CH):
return str (CH). Upper ()
#对给定字符串中的每个字母应用to_upper函数
Print (Map (to_upper, "ASDFASDFUASDLAKSDJF". Split ()))
#主要使用一个基于布尔值得函数对元素进行过滤
Def Filter_demo ():
def is_alnum (CH):
Return Ch.isalnum ()
#!se will be filtered out.
Test_list = [' SDAs ', ' 123d ', '!se ', ' Sun Astifen ']
#基于具体函数
Print (List filter (Is_alnum, test_list))
#基于列表推导
Print (list (x for x in Test_list if X.isalnum ()))
#基于匿名函数
Print (List filter (lambda x:x.isalnum (), test_list))
#reduce的主要功能是利用列表中的两个元素迭代调用某个函数 and finally get a result
#在python3中要显示的添加 from functools Import reduce
#本例中运行的过程大致是先是1 +2=3, use 3+4=7,7+4 ...
Def Reduce_demo ():
Print (Reduce (lambda x, y:x + y, Range (1, 10))
#利用sum函数累加列表中的值
Def Sum_demo ():
Print (SUM (range (10))
if __name__ = = "__main__":
#map_demo ()
#filter_demo ()
#reduce_demo ()
Sum_demo ()