Python学习笔记(九) map、zip和filter函数

这篇文章主要介绍 Python 中几个常用的内置函数,用好这几个函数可以让自己的代码更加 Pythonnic 哦

1、map

map() 将函数 func 作用于序列 seq 的每一个元素,并返回处理后的结果,其语法格式如下:

map(func, seq)

其中,func 为处理函数,seq 为序列,该方法返回一个迭代器对象,可以使用 list() 方法使其变成列表类型

以下是一个例子:

>>> res = map(lambda x: x**2, [1,2,3])
>>> type(res)
# <class 'map'>
>>> print([item for item in res])
# [1, 4, 9]

该方法还接受多个序列作为参数,其语法格式如下:

map(func, seq1, seq2, … seqM)

其中,func 为处理函数,seq1 ... seqM 为序列

以下是一个例子:

>>> res = map(lambda x,y : x+y, [1,2,3], [4,5,6])
>>> type(res)
# <class 'map'>
>>> print([item for item in res])
# [5, 7, 9]

2、zip

zip() 函数用于打包序列,其语法格式如下:

zip(seq1, seq2, … seqM)

其中,seq1 ... seqM 为序列,该方法返回一个迭代器对象

注意,若提供的序列长度不同,则返回的对象长度与最短序列的长度相同

以下是一个例子:

>>> res = zip([1,2,3],[4,5,6])
>>> # 类似于 res = map(lambda x,y : (x,y), [1,2,3], [4,5,6])
>>> type(res)
# <class 'zip'>
>>> print([item for item in res])
# [(1, 4), (2, 5), (3, 6)]

3、filter

filter() 函数用于过滤序列,根据 func 的作用结果进行过滤,其语法格式如下:

filter(func, seq)

其中,func 为处理函数,seq 为序列,该方法返回一个迭代器对象

以下是一个例子:

>>> res = filter(lambda x : x%2==0, [1,2,3,4,5,6])
>>> type(res)
# <class 'filter'>
>>> print([item for item in res])
# [2, 4, 6]

【 阅读更多 Python 系列文章,请看 Python学习笔记

版权声明:本博客属于个人维护博客,未经博主允许不得转载其中文章。
原文地址:https://www.cnblogs.com/wsmrzx/p/10545793.html