python中map、reduce、filter、自定义排序函数、装饰器函数和偏函数

import functools
from functools import reduce

# map()是python内置高阶函数,功能是接收一个函数和一个list
# 把函数f依次作用在list的每一个元素上,得到一个新的list并返回。
# 例1. 把list的每个元素都做平方并返回
def f(x):
    return x * x

print(list(map(f, [1, 2, 3, 4, 5])))
print(list(map(lambda x: x*x, [1, 2, 3, 4, 5])))  # 利用匿名函数lambda

# 注意:由于list可以包含任意类型的元素,故map()不仅可以处理只包含数值的list
# 还可以处理包含任意类型的list,只要传入的函数f能处理该数据类型

# reduce()函数也是python内置高阶函数,接收的参数和map()类似,一个函数f和一个list,但行为有所不同
# reduce传入的f必须接收两个参数,对list的每个元素反复调用函数f,并返回最终结果值
# 例1. 对list中的所有元素求和
def f(x, y):
    return x + y

reduce(f, [1, 2, 3, 4, 5])

# reduce还可以接收第三个可选参数,作为计算初始值
# 例2. 对list中所有元素求和,并加上100
def f(x, y):
    return x + y

reduce(f, [1, 2, 3, 4, 5], 100)


# filter函数是python内置的另一有用的高阶函数,它接收一个函数f和一个list,函数f对每个元素进行判断
# 返回True或False,filter根据判断结果自动给过滤掉不符合条件的元素,返回又符合条件的元素组成的新list
# 例1. 从list中删除偶数,保留奇数
def isOdd(x):
    return x % 2 == 1

filter(isOdd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])

# 例2. 删除None或空字符串
def isNotEmpty(s):
    return s and len(s.strip()) > 0

filter(isNotEmpty, ['test', None, '', ' '])


# sort()也是高阶函数,可以接收一个比较函数来实现自定义排序,比较函数的定义是:传入两个带比较的元素x,y
# 如果x<y则返回-1,x>y则返回1,x=y则返回0
# 例1. 对list进行排序
sorted([3, 6, 2, 7, 38, 9])
# 例2. 如果我们要实现倒序排序,只需自己编写一个reversedCmp函数
def reversedCmp(x, y):
    if x > y:
        return -1
    if x < y:
        return 1
    return 0

# sorted([5,3,6,4,1,7],reversedCmp) #python3已经不支持了
print(sorted(['bus','amount','Zero','Ceiling'], key=None))


# 装饰器
def fPrint(f): #装饰器函数
    def fn(x):
        print('call '+f.__name__+"()")
        return f(x)
    return fn

def f1(x):
    return x * x

# f1 = fPrint(f1)
# 等价于
@fPrint
def f1(x):
    return x*x

print(f1.__name__)  # 可以看到函数名已经不是'f1',而是@fPrint内部定义的'fn'
# 所以对于那些依赖函数名的代码就会失效,而且decorator还改变了函数的__doc__等其他属性
# 如果要让调用者看不出一个函数经过了@decorator的"改造",就需要把原函数的一些属性复制到新函数中
def fPrint(f): #装饰器函数
    @functools.wraps(f)
    def fn(x):
        print('call '+f.__name__+"()")
        return f(x)
    return fn
@fPrint
def f1(x):
    return x*x
print(f1.__name__)  # 这样函数名就变为'f1'了

print(f1(2))
int('1010101')  # 默认是十进制
int2 = functools.partial(int, base=2)  # 利用偏函数设置参数为二进制的新函数
int2('1010101')
发布了49 篇原创文章 · 获赞 95 · 访问量 23万+

猜你喜欢

转载自blog.csdn.net/Trisyp/article/details/78832303