python入门16 递归函数 高阶函数

递归函数:函数内部调用自身。(要注意跳出条件,否则会死循环)

高阶函数:函数的参数包含函数

递归函数

#coding:utf-8
#/usr/bin/python
"""
2018-11-17
dinghanhua
递归函数 高阶函数
"""

'''递归函数,函数内部调用函数本身'''
'''n!'''
def f_mul(n):
    if type(n) != type(1) or n <= 0: #不是整数或小于0
        raise Exception('参数必须是正整数')
    elif n == 1:
        return 1
    else:
        return n * f_mul(n-1) #调用自身

print(f_mul(5))
''''回声函数'''
def echo(voice):
    if len(voice) <= 1:
        print(voice)
    else:
        print(voice,end = '\t')
        echo(voice[1:]) #调用自身

echo('你妈妈叫你回家吃饭')

高阶函数

'''函数式编程:函数的参数是函数。高阶函数'''

'''map() 2个参数:1个函数,1个序列。将函数作用于序列的每一项并返回list
map(f,[l1,l2,l3]) = [f(l1),f(l2),f(l3)]
'''
#列表每项首字母大写
print(list(map(lambda x: x.capitalize(),['jmeter','python','selenium'])))

#并行遍历,序列合并
print(list(map(lambda x,y,z:(x,y,z),[1,2,3],['jmeter','python','selenium'],['api','dev','ui'])))
#等价于
print(list(zip([1,2,3],['jmeter','python','selenium'],['api','dev','ui'])))
#3个列表各项平方之和
print(list((map(lambda x,y,z:x**2+y**2+z**2,[1,2,3],[4,5,6],[7,8,9]))))
'''filter() 用函数筛选,函数需返回bool值。true保留,false丢弃
filter(f,[l1,l2,l3]) = [ if f(l1)==True: l1,...]
'''

#取出列表内的偶数
li = [1,334,32,77,97,44,3,8,43]
print(list(filter(lambda x:x%2==0,li)))

#取出列表中去除两边空格后的有效数据 x and x.strip()
li=[False,'','abc',None,[],{},set(),'  ','x',[1,2]]
print(list(filter(lambda x: x and str(x).strip(),li)))
'''自定义高阶函数'''
def add_square(x,y,f):
    return f(x)+f(y)

def square(x):
    return x**2

print(add_square(1,2,square))
#用匿名函数
print(add_square(1,2,lambda x:x**2))

the end!

猜你喜欢

转载自www.cnblogs.com/dinghanhua/p/9975142.html