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)