Special methods for function processing in Python _python

Source: Internet
Author: User
Tags in python

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 ()

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.