1.函数递归
函数在调用阶段直接或间接的调用本身
def index(): print('from index') login() def login(): print('from login') index() index() # 函数不会无限次的递归下去
递归分为两个阶段
1.回溯:重复的过程,重复的过程建立在问题简单化,最终有一个结束条件
2.递归:往回推的过程
def age(n): if n == 1: return 18 return age(n-1) + 2 res = age(5) print(res) #26
l = [1,[2,[3,[4,[5,[6,[7,[8,[9,[10,[11,[12,[13,]]]]]]]]]]]]] def get_num(l): for i in l: if type(i) is int: print(i) # 1,2,3,4,5,6,7,8,9,10,11,12,13 else: get_num(i) get_num(l)
递归函数不考滤循环次数,只需要把握结束的条件即可
二分法:容器类型里面的数字必须有大小顺序
l = [1,3,5,12,57,89,101,103,123,146,167,179,189,345] target_num = 103 def get_num(l,target_num): if not l: print('哈哈') return middle_index = len(l) // 2 # 获取列表中间的索引 if target_num > l[middle_index]: # 判断target与中间索引的大小 num_right = l[middle_index + 1:] # 切取列表右半部分 get_num(num_right,target_num) # 在递归调用给get_num函数 elif target_num < l[middle_index]: num_left = l[0:middle_index] # 切取列表左半部分 get_num(num_left, target_num) # 在递归调用get_num函数 else: print('find it',target_num) get_num(l,target_num)
x = 3 y = 7 res = x if x > y else y print(res) #7
当 if 后面的条件成立时返回 if 前面的值,否则返回 else 后面的值
值1 if 条件 else 值2
l = ['tank','nick','oscar','sean'] res = ['%s_DSB'%name for name in l] print(res) # ['tank_DSB', 'nick_DSB', 'oscar_DSB', 'sean_DSB']
l = ['tank_DSB', 'nick_DSB', 'oscar_DSB', 'sean_DSB','jason_NB'] res = [name for name in l if name.endswith('_DSB')] print(res) # ['tank_DSB', 'nick_DSB', 'oscar_DSB', 'sean_DSB']
# for循环依次取出列表里的元素,给if判断,如果不成立,舍弃
l1 = ['name','password','hobby']
l2 = ['jason','123','DBJ','egon']
d = {}
for i,j in enumerate(l1):
d[j] = l2[i]
print(d) # {'name': 'jason', 'password': '123', 'hobby': 'DBJ'}
l1 = ['jason','123','read']
d = {i:j for i,j in enumerate(l1) if j != '123'}
print(d) # {0: 'jason', 2: 'read'}
lambda x,y:x+y # 左边相当于函数形参,右边相当于函数的返回值,匿名函数通常不会单独使用,需要配合内置函数一起使用
d = {
'egon':30000,
'jason':88888888888,
'nick':3000,
'tank':1000
}
print(max(d,key=lambda name:d[name])) # jason
map 映射
l = [1,2,3,4,5,6]
print(list(map(lambda x:x+5,l))) # [6, 7, 8, 9, 10, 11]
zip 拉链
l1 = [1,2,]
l2 = ['jason','egon','tank']
l3 = ['a','b','c']
print(list(zip(l1,l2,l3))) # [(1, 'jason', 'a'), (2, 'egon', 'b')]
l = ['jason','egon','nick','tank']
print(sorted(l,reverse=True)) # ['tank', 'nick', 'jason', 'egon']
from functools import reduce
l = [1,2,3,4,5,6]
print(reduce(lambda x,y:x+y,l,19)) # 40 19初始值,第一个参数,如果不存在,第一次获取两个,之后再一个一个获取