Python3:lambda,map,filter built-in functions

Source: Internet
Author: User
Tags iterable

NOTES: Reference Documents-(rookie tutorial) http://www.runoob.com/python/python-built-in-functions.html

Reference Document-(demon white) http://blog.csdn.net/qq_24753293/article/details/78337818

I. Lambda ()

Describe:

简化def函数

Instance:

A=lambda x:x+1理解为:def A(x):    return x+1冒号左边→想要传递的参数冒号右边→想要得到的数(可能带表达式)

Two. Map ()

Describe:

map(function, iterable, ...)会根据提供的函数对指定序列做映射,返回迭代器

Instance:

>>>def square(x) :            # 计算平方数...     return x ** 2... >>> list(map(square, [1,2,3,4,5]))   # 计算列表各个元素的平方[1, 4, 9, 16, 25]>>> list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))  # 使用 lambda 匿名函数[1, 4, 9, 16, 25] # 提供了两个列表,对相同位置的列表数据进行相加>>> list(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))[3, 7, 11, 15, 19]#如果函数有多个参数, 但每个参数的序列元素数量不一样, 会根据最少元素的序列进行:>>> listx = [1,2,3,4,5,6,7]       # 7 个元素>>> listy = [2,3,4,5,6,7]         # 6 个元素 >>> listz = [100,100,100,100]     # 4 个元素>>> list_result = map(lambda x,y,z : x**2 + y + z,listx, listy, listz)>>> print(list(list_result))[103, 107, 113, 121]

Three. Filter ()

Describe:

filter(function, iterable) 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新迭代器

Instance:

#只有序列中的元素执行函数(is_odd)为true时,才被用于构建新的迭代器>>> def is_odd(n):...     return n%2 == 1...>>> newlist = filter(is_odd,[1, 2, 3, 4, 5, 6, 7, 8, 9, 10])>>> print(newlist)<filter object at 0x00000227B33F8198>>>> print(list(newlist))[1, 3, 5, 7, 9]#用map函数模仿filterlist(map(lambda x:x-5 if x>5 else x,[4,5,6]))[4, 5, 1]#理解: if为true,执行lambda表达式,if为false,执行 else 表达式#用map函数模仿filter,必须要有"else">>> list(map(lambda x:x-5 if x>5 ,[4,5,6]))  File "<stdin>", line 1    list(map(lambda x:x-5 if x>5 ,[4,5,6]))                                 ^SyntaxError: invalid syntax

Python3:lambda,map,filter built-in 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.