目录
异常处理:
def forl(iterable):
iterator = iterable.__iter__()
while True:
try:
print(iterator.__next__())
except Exception as e:
print(e)
break
forl([1,2,3,4,5,6,7,8,9])
迭代器
迭代器:迭代的工具。迭代是更新换代,迭代也可以说成是重复,并且但每一次的重复都是基于上一次的结果来的
--python中一切皆对象
迭代器对象: 含有__iter__
方法的对象
--总结:
可迭代对象:
-
python中内置str、list、tuple、dict、set、file(除了数字类型)
-
内置含有
__iter__
方法的对象
--只有字符串和列表以来索引取值。其他可迭代类型无法依赖索引取值。
迭代器对象:
可迭代对象执行__iter__
方法得到的返回值,并且可迭代对象会有一个__next___
方法
特点:
1.内置__next__
方法,执行该方法会拿到迭代器对象中一个值
2.内置有__iter__
方法,执行该方法会拿到迭代器本身
3。文件本身就是一个迭代器对象
缺点:
1.取值麻烦,只能一个一个取,并且只能往后取,值取了就没有
2.无法使用len()
方法获取长度
FOR循环原理:
--for 循环-》迭代器循环,in后面必须是可迭代的对象
因为迭代器使用__iter__
后还是迭代器本身,因此for循环不用考虑in后面的对象是可迭代对象还是迭代器对象
迭代器:
可迭代对象使用__iter__
方法后变成一个可迭代器对象,这个迭代器对象只是占用了一小块内存空间,只有使用__next__
后才会取出一个值。
三元表达式:
x = 20
y = 10
print(f"x if x > y else y: {x if x >y else: y}")
列表推导式(算法):
it = [i for i in range(10)]
it = [i**2 for i in range(10)]
# i**2 -->改变 ,range(n) --可迭代对象
print(it)
字典生成式:
dic = {}
dic = {i:i*2 for i in range(10)}
print(dic)
ZIP方法:(两个列表)--》通过解压缩函数生成一个字典
it1 = ['a','b','c']
it2 = ['1','2','3']
dic = {k: v for k,v in zip(it1,it2)}
print(dic)
for -- 循环内有常处理
生成器 :
--含有关键字yield的函数
yield的英语单词的意思是生产,在函数中凡是出现yield关键字,在调用函数时,就不会继续执行函数的代码,而是会返回一个值
-生成器的本质就是迭代器,同时不仅仅是迭代器。
yield:
1.提供一种自定义迭代器的方式
2.可以暂停住函数,并提供当前的返回值
yield / return 的区别:
相同点:两者都是在函数内部使用,都可以返回值,并且返回值没有类型合格书的限制。
不同点:return只能返回一次值,yield可以返回多次值
生成器表达式:
1.把列表推导式的[] 换成() 就是生成器表达式
2.有点:节省内存,一次只有一个值在内存中
t = (i for i in range(10))
print(t)
print(f"next(t): {next(t)}”)
生成器表达式和列表推导式的区别:
列表推导式相当于直接给你一筐蛋,而生成器表达式相当于给你一只老母鸡
递归
函数的嵌套调用:函数嵌套函数,
函数的递归调用:是一种特殊的嵌套调用,但是它在调用一个函数的过程中,又直接或间接地调用了它自身。
死递归:递归函数不断地调用函数自身,那么这个递归函数将会进入一个死循环---》定义函数就会开辟内存空间
直接调用指的是:直接在函数内部调用函数自身
修改调用层数:
import sys
sys.setrecursionlimit(10000)
def foo(n):
print('from foo',n)
foo(n+1)
foo(0)
间接调用指的是:不在原函数体内调用函数自身,而是通过其他的方法间接调用函数自身。
递归两个阶段:
1.递推:一层一层递归调用下去,进入下一层递归的问题规模都将会缩小
2.回溯: 递归必须要有一个明确的结束条件,在满足该条件开始一层一层回溯
递归的精髓在于通过不断的重复逼近一个最终的结果
递归的本质:干重复的·活
原则: 1.有控制结束的条件
2.递归必须要有规律
二分法应用:
nums = [1,3,7,11,22,34,55,78,111,115]
for item in nums:
if item == 10:
print('find it')
break
else:
print('not exists')
列表元素多:--二分查找
def search(search_num, nums):
mid_index = len(nums)//2
print(nums)
if not nums:
print('not exists')
return
if search_num > nums[mid_index]:
# in the right
nums = nums[mid_index+1:] #切片
search(search_num, nums)
elif search_num < nums[mid_index]:
# in the left
nums = nums[:mid_index]
search(search_num, nums)
else:
print('find it')
search(7, nums)