python学习笔记1

一、递归

1 def fact(num):
2     if num == 1:
3         return 1
4     result = n*fact(n-1)
5         return result

递归特性:

  1、调用自身函数

  2、必须有结束条件

  3、但凡用递归可以解决的循环都可以解决

  4、递归的效率在很多时候很低,不推荐使用

二、重要的内置函数

1 #匿名函数 lambda
2 add = lambda a,b : a + b
3 add(1, 2)
4 
5 #使用匿名函数实现阶乘
6 res = reduce(lambda x,y : x*y , range(1,10))
7 print(res)
 1 #reduce(function,sequence,starting_vlaue)
 2 from functools import reduce
 3 
 4 def add(x, y)
 5     return x + y
 6     
 7 res = reduce(add, range(1,101))
 8 print(res)            #5050
 9 
10 res = reduce(add, range(1,101), 20)
11 print(res)            #5070
1 #map(fun1,str)
2 str = ['a','b','c','d']
3 
4 def fun1(s)
5     return s + 'speak'
6     
7 ret = map(fun1,str)
8 print(list(ret))
1 #filter(fun1,str)
2 str = ['a','b','c','d']
3 def fun1(s)
4     if s != 'a':
5         return s
6 
7 ret = filter(fun1,str)   #ret是一个迭代器对象
8 print(list(ret))  
9 #str中的item一次执行fun1(item),将执行结果为True的item做成一个filter object的迭代器返回。可以看做过滤函数
原文地址:https://www.cnblogs.com/xjklmycw/p/9463657.html