您的位置:首页 > 编程语言 > Python开发

【脚本语言系列】关于Python基础知识映射器和过滤器,你需要知道的事

2017-07-14 16:56 811 查看

如何使用映射器(Map)和过滤器(Filter)

如何使用映射器(Map)

map(function, list_of_inputs)

- for循环实现

# -*- coding:utf-8 -*-
items = [1, 2, 3, 4, 5]
squared = []
cubed = []
for i in items:
squared.append(i**2)
cubed.append(i**3)

print items, squared, cubed


[1, 2, 3, 4, 5] [1, 4, 9, 16, 25] [1, 8, 27, 64, 125]


Lambdas表达式实现

# -*- coding:utf-8 -*-
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x : x ** 2, items))
cubed = list(map(lambda x : x ** 3, items))
print items, squared, cubed

def pow2(x):
return x*x
def pow3(x):
return x*x*x
squared = list(map(lambda x : pow2(x), items))
cubed = list(map(lambda x : pow3(x), items))
print items, squared, cubed

print "\n"

funcs = [pow2, pow3]
for i in range(5):
value = list(map(lambda x: x(i), funcs))
print value


[1, 2, 3, 4, 5] [1, 4, 9, 16, 25] [1, 8, 27, 64, 125][1, 2, 3, 4, 5] [1, 4, 9, 16, 25] [1, 8, 27, 64, 125]
[0, 0]
[1, 1]
[4, 8]
[9, 27]
[16, 64]


如何使用过滤器(Filter)

# -*- coding:utf-8 -*-
items = range(-5, 5)
lt_zero = list(filter(lambda x: x < 0, items))
print lt_zero


[-5, -4, -3, -2, -1]


什么是映射器(Map)和过滤器(Filter)

映射器(Map):函数映射到输入列表的所有元素;

过滤器(Filter):函数映射到输入列表的所有元素并创建出一个对每个元素返回True的列表;

为何使用映射器(Map)和过滤器(Filter)

能够为函数式编程提供便利;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐