Python中map、filter、zip、reduce用法

Python中map、filter、zip、reduce用法

map

它接收一个函数 f() 和一个 list,遍历 list 中的元素来调用函数 f ,得到一个新的 list 并返回。
格式: map(function, sequence)

Test1-求列表每个元素的平方
def s(num):
    return num * num

l = [1, 2, 3]
result = map(s, l)
print(list(result))

Out: [1, 4, 9]
Test2-两个列表对位求和
l1 = [1, 2, 3]
l2 = [4, 5, 6]

result = map(lambda x, y: x+y, l1, l2)
print(list(result))

Out: [5, 7, 9]

filter

筛选函数。
它接收一个函数 f() 和一个 list。遍历 list 中的元素调用 f ,将符合条件的组成一个新列表
格式: filter(function, sequence)

Test1-求奇数
def s(num):
    if num % 2 != 0:
        return num

l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = filter(s, l1)
print(list(result))

Out: [1, 3, 5, 7, 9]
Test2-map和filter的区别
l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = filter(lambda n: n % 2 != 0, l1)
print('filter: {}'.format(list(result)))

result = map(lambda n: n % 2 != 0, l1)
print('map: {}'.format(list(result)))

Out: filter: [1, 3, 5, 7, 9]
Out: map: [True, False, True, False, True, False, True, False, True]

zip

打包计算
接收一系列可迭代对象,将他们组合成元组

Test1-构建字典
l1 = ['a', 'b', 'c']
l2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
result = zip(l1, l2)
print(dict(result))

Out: {'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]}

reduce

累积运算
它接收一个函数 f() 和一个 list,将 list 中的多个元素调用 f ,将得到的结果再和后面的元素组合调用 f 。
python3中。reduce被移到 functools 方法中。调用方法:
from functools import reduce

Test1-实现类似阶乘的效果
from functools import reduce
l1 = [1, 2, 3, 4]
result = reduce(lambda x, y: x * y, l1)
print(result)

Out: 24
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值