P进阶_(reduce函数)

# coding:utf-8

# 当前的项目名:code

# 当前编辑文件名:reduce_mian

# 当前系统日期:2022/7/28 0028

源码:

  reduce(function, sequence[, initial]) -> value

    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.

定义:


    reduce(function, sequence[, initial]) -> value 将两个参数的函数从左到右累积应用于序列的项目,从而将序列缩减为单个值。
    例如,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 计算 ((((1+2)+3)+4)+5)。
    如果 initial 存在,则在计算中将其放置在序列的项目之前,并在序列为空时用作默认值。

    相当于前一个相加的值等于后一个值的最前值 ,前一个值是函数,函数传入参数为2,一般用lambda

例子:

from functools import reduce


def reduce_fun(x, y):
    return x, y


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


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


def reduce_fun3(x, y):
    return x * 10 + y


res0 = reduce(reduce_fun, [1, 2, 1])  # ((1, 2), 1)
res00 = reduce(reduce_fun, [1, 2])  # (1, 2)
res1 = reduce(reduce_fun, [1, 2])  # (1, 2)
res2 = reduce(reduce_fun2, [1, 2, 1])  # 1+2+1 =4
res3 = reduce(reduce_fun3, [1, 2, 1])  # 1*10+2=12 12*10+1=121 ,这里改变的是x值
print(res0)
print(res00)
print(res1)
print(res2)
print(res3)

lambda 函数

int_d = [1, 2, 3, 4]
print(reduce(lambda x, y: x + y, int_d))  # 1+2+3+4=10

dict_data = {6: 9, 10: 5, 3: 11, 8: 2, 7: 6}
test_data_1 = sorted(dict_data.items(), key=lambda x: x[0])
print(test_data_1)

print(sorted([1,2,9,8]))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值