Python map()函数、filter()函数、reduce()函数

一、map() 函数

1、描述

  • map() 会根据提供的函数对指定序列做映射。
  • 第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
  • map中第一个参数(函数),会作用在每一个可迭代元素上面

2、语法

map(function, iterable, …)

3、参数

  • function – 函数
  • iterable – 一个或多个序列

4、返回值

  • Python 2 返回列表
  • Python 3 返回迭代器

5、举例

# 计算平方数
def square(x) :            
    return x ** 2
    
print(list(map(square, [1,2,3,4,5])))	# 使用的是python3,假如不加list,就是一个迭代器
# 使用 lambda 匿名函数

# 对列表元素,求平方数
print(list(map(lambda x: x ** 2, [1, 2, 3])))
# [1, 4, 9]              

# 提供了两个列表,对相同位置的列表数据进行相加
print(list(map(lambda x , y: x + y, [1,2,3] , [4,5,6])))    
# [5, 7, 9]

print(list(map(str, [1, 2, 3, 4])))
['1', '2', '3', '4']

print(list(map(int,'1234')))
[1, 2, 3, 4]

二、filter() 函数

1、描述

  • filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。
  • 该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判,然后返回 True 或 False,最后将返回 True 的元素放到新列表中

2、语法

filter(function, iterable)

3、参数

  • function – 判断函数。
  • iterable – 可迭代对象。

4、返回值

返回一个迭代器对象

5、举例

# 过滤出列表中所有的偶数
def is_ou(n):
    return n % 2 == 0

res_ou = list(filter(is_ou,[1,2,3,4,5,6]))
print(res_ou)
# [2, 4, 6]

# 匿名函数
print(list(filter(lambda x:x%2==0,[1,2,3,4,5,6])))
# [2, 4, 6]

# 过滤出列表中所有的奇数
def is_ji(n):
    return n % 2 == 1

res_ji = list(filter(is_ji,[1,2,3,4,5,6]))
print(res_ji)
# [1, 3, 5]


# 匿名函数
print(list(filter(lambda x:x%2==1,[1,2,3,4,5,6])))
# [1, 3, 5]

print(list(map(lambda x:x%2==1,[1,2,3,4,5,6])))
# [True, False, True, False, True, False]

# 过滤出1~100中的平方根是整数的数
import math
def is_sqr(x):
    return math.sqrt(x) % 1 == 0

res = list(filter(is_sqr,range(1,101)))
print(res)
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


# 匿名函数
print(list(filter(lambda x:math.sqrt(x)%1==0,range(1,101))))
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

三、reduce() 函数

1、描述

  • reduce() 函数会对参数序列中元素进行累积。
  • 函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果。
  • reduce() 函数出现在python2中;
  • 在python3中调用,使用(from functools import reduce)

2、语法

reduce(function, iterable[, initializer])

3、参数

  • function – 函数,有两个参数
  • iterable – 可迭代对象
  • initializer – 可选,初始参数

4、返回值

返回函数计算结果。

5、举例

# 求和
from functools import reduce

def add(x,y):
    return x + y

print(reduce(add,[1,2,3]))
# 6


# 匿名函数
print(reduce(lambda x, y: x+y, [1,2,3]))
# 6

# 求积
from functools import reduce

def prod(x,y):
    return x * y

print(reduce(prod,[1,2,3,4]))
# 24


# 匿名函数
print(reduce(lambda x, y: x*y, [1,2,3,4]))
# 24
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值