【python进阶教程】python函数式编程与应用

map 映射

  • 源码中的注释
    “”"
    map(func, *iterables) --> map object

Make an iterator that computes the function using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.
“”"

list1 = [1,2,3,4,5,6,7,8]
list2 = [1,2,3,4,5,6,7,8]
a = map(lambda x, y:x*x + y,list1,list2)
print(list(a))

reduce 归约 会做一个连续的计算 连续的调用lambda

  • 源码中的注释
    “”"
    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.
“”"

from functools import reduce
list1 = [1,2,3,4,5,6,7,8]
list2 = ['1','2','3','4','5','6','7','8']
# reduce(function, sequence[, initial]) -> value
a = reduce(lambda x, y:x + y, list1) # list1相加
a = reduce(lambda x, y:x + y, list1, 10) # 初始值为10 list1相加
a = reduce(lambda x, y:x + y, list2, 'sum') # 初始值为10 list1相加
print(a)

filter 集合的过滤

  • 源码中的注释

“”"
filter(function or None, iterable) --> filter object

Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true.
“”"

list1 = [1,0,1,0,1,0,1]
res = filter(lambda x: True if x==1 else False, list1)
print(list(res))

命令式编程

    # def
    # if else
    # for

函数式编程

    # map reduce filter
    # lambda 算子

理论上可以使用后者替换前者

    # def: lambda
    # if else: 三元表达式
    # for: map reduce

三元表达式

a = 1
b = 2

# 第一种写法:
erroStr = "More" if a > b else "Less"
print(erroStr) # 运行结果为:Less
# 第二种写法:
print({True: "More", False: "Less"}[a > b]) # 运行结果为:Less
# 第三种写法:
print(("FalseValue", "TrueValue")[a > b]) # 运行结果为:FalseValue
print(("Less", "More")[a > b]) # 运行结果为:Less

应用

L = []
x = 2
L.append(100 if x > 1 else 0)


def Max(x, y):
   return x if x > y else y

def fib(n):
   return 1 if n == 1 else fib(n-1) + n
fib(2)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不走小道

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值