迭代器知识点积累
主要内容:
1.函数名的使用以及第一类对象
2.闭包
3.迭代器
一.函数名的运用.
函数名是一个变量.但它是一个特殊的变量.与括号配合可以执行函数的变量.
1.函数名的内存地址
def func(): print("呵呵") print(func) 结果: <function func at 0x1101e4ea0> #此乱码为函数内存地址
2.函数名可以赋值给其他变量
def func(): print("呵呵") print(func) a=func #把函数当成一个变量赋值给另一个值 a=() #函数调用 func()
3.函数名可以当做容器类的元素
def func1(): print("呵呵") def func2(): print("呵呵") def func3(): print("呵呵") def func(): print("呵呵") lst = [func1,func2,func3] for i in lst: i()
4.函数可以当函数的参数
def func(): print("吃了么") def func2(fn): print("我是func2") fn() # 执⾏传递过来的fn print("我是func2") func2(func) # 把函数func当成参数传递给func2的参数fn.
5.函数名可以作为函数的返回值
def func_1(): print("这⾥是函数1") def func_2(): print("这⾥是函数2") print("这⾥是函数1") return func_2 fn = func_1() # 执⾏函数1. 函数1返回的是函数2, 这时fn指向的就是上⾯函数2 fn() # 执⾏上⾯返回的函数
二.闭包
什么是闭包? 闭包就是内层函数,对外层函数(非全局)的变量的引用.叫闭包
def func1(): name = "alex" def func2(): print(name) # 闭包 func2() func1() 结果: alex
我们可以使用__closure__来检测函数是否是闭包.使用函数名.__closure__返回cell就是闭包
返回None就不是闭包
def func1(): name = "alex" def func2(): print(name) # 闭包 func2() print(func2.__closure__) # (<cell at 0x10c2e20a8: str object at 0x10c3fc650>,) func1()
问题,如果在函数外边调用内部函数呢?
def outer(): name = "alex" # 内部函数 def inner(): print(name) return inner fn = outer() # 访问外部函数, 获取到内部函数的函数地址 fn() # 访问内部函数
那如果多层嵌套呢? 很简单,只需要一层一层的往外层返回就行了
def func1(): def func2(): def func3(): print("嘿嘿") return func3 return func2 func1()()()
由它我们可以引出闭包的好处. 由于我们在外界可以访问内部函数. 那这个时候内部函 数访问的时间和时机就不⼀定了, 因为在外部, 我可以选择在任意的时间去访问内部函数. 这 个时候. 想⼀想. 我们之前说过, 如果⼀个函数执⾏完毕. 则这个函数中的变量以及局部命名 空间中的内容都将会被销毁. 在闭包中. 如果变量被销毁了. 那内部函数将不能正常执⾏. 所 以. python规定. 如果你在内部函数中访问了外层函数中的变量. 那么这个变量将不会消亡. 将会常驻在内存中. 也就是说. 使⽤闭包, 可以保证外层函数中的变量在内存中常驻. 这样做 有什么好处呢? 非常⼤的好处. 我们来看⼀个关于爬⾍的代码:
from urllib.request import urlopen def but(): content = urlopen("http://www.xiaohua100.cn/index.html").read() def get_content(): return content return get_content fn = but() # 这个时候就开始加载校花100的内容 # 后⾯需要⽤到这⾥⾯的内容就不需要在执⾏⾮常耗时的⽹络连接操作了 content = fn() # 获取内容 print(content) content2 = fn() # 重新获取内容 print(content2)
综上,闭包的作用就是让一个变量能够常驻内存.供后面的程序使用.
三.迭代器
我们之前⼀直在⽤可迭代对象进⾏迭代操作. 那么到底什么是可迭代对象. 本⼩节主要讨 论可迭代对象. ⾸先我们先回顾⼀下⽬前我们所熟知的可迭代对象有哪些:
str, list, tuple, dict, set. 那为什么我们可以称他们为可迭代对象呢? 因为他们都遵循了可 迭代协议. 什么是可迭代协议. ⾸先我们先看⼀段错误代码:
#对的 s = "abc" for c in s : print(c) #错的 for i in 123: print(i)
结果:
Traceback (most recent call last):
File "/Users/sylar/PycharmProjects/oldboy/iterator.py", line 8,
in <module>
for i in 123:
TypeError: 'int' object is not iterable
注意看报错信息中有这样⼀句话. 'int' object is not iterable . 翻译过来就是整数类型对象 是不可迭代的. iterable表⽰可迭代的. 表⽰可迭代协议. 那么如何进⾏验证你的数据类型是否 符合可迭代协议. 我们可以通过dir函数来查看类中定义好的所有⽅法.
s = "我的哈哈哈" print(dir(s)) # 可以打印对象中的⽅法和函数 print(dir(str)) # 也可以打印类中声明的⽅法和函
在打印结果中.寻找__iter__如果能找到.那么这个类的对象就是一个可迭代对象.
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
我们发现在字符串中可以找到__iter__.继续看一下list,tuple,dict,set
print(dir(tuple)) print(dir(list)) print(dir(open("护⼠少妇嫩模.txt"))) # ⽂件对象 print(dir(set)) print(dir(dict))
结果: ['__add__', '__class__', '__contains__', '__delattr__', '__dir__',
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__getnewargs__', '__gt__', '__hash__',
'__init__', '__init_subclass__', '__iter__', '__le__', '__len__',
'__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__', 'count', 'index'] ['__add__', '__class__',
'__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__',
'__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count',
'extend', 'index', 'insert', 'pop', 'remove', 'reverse',
'sort'] ['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__',
'__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__'
, '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__',
'__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__',
'__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed',
'_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing',
'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno',
'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read',
'readable', 'readline', 'readlines', 'seek', 'seekable', 'tell',
'truncate', 'writable', 'write', 'writelines'] ['__and__', '__class__',
'__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__',
'__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__',
'__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__',
'__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__',
'__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__',
'__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__',
'add', 'clear', 'copy', 'difference', 'difference_update', 'discard',
'intersection', 'intersection_update', 'isdisjoint', 'issubset',
'issuperset', 'pop', 'remove', 'symmetric_difference',
'symmetric_difference_update',
'union', 'update'] ['__class__', '__contains__', '__delattr__',
'__delitem__', '__dir__', '__doc__', '__eq__', '__format__',
'__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__',
'__init__', '__init_subclass__', '__iter__', '__le__', '__len__',
'__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__',
'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem',
'setdefault', 'update', 'values']
我们发现这几个可以进行for循坏的东西都有__iter__函数,包括range也有.可以自己试一下.
这是查看⼀个对象是否是可迭代对象的第⼀种办法. 我们还可以通过isinstence()函数来查 看⼀个对象是什么类型的
l = [1,2,3] l_iter = l.__iter__() from collections import Iterable from collections import Iterator print(isinstance(l,Iterable)) #True print(isinstance(l,Iterator)) #False print(isinstance(l_iter,Iterator)) #True print(isinstance(l_iter,Iterable)) #True
综上.我们可以确定. 如果对象中有__iter__函数. 那么我们认为这个对象遵守了可迭代协议. 就可以获取到相应的迭代器. 这⾥的__iter__是帮助我们获取到对象的迭代器. 我们使⽤迭代 器中的__next__()来获取到⼀个迭代器中的元素. 那么我们之前讲的for的⼯作原理到底是什 么?
继续看代码
s = "我爱北京天安⻔" c = s.__iter__() # 获取迭代器 print(c.__next__()) # 使⽤迭代器进⾏迭代. 获取⼀个元素 我 print(c.__next__()) # 爱 print(c.__next__()) # 北 print(c.__next__()) # 京 print(c.__next__()) # 天 print(c.__next__()) # 安 print(c.__next__()) # ⻔ print(c.__next__()) # StopIteration #打印数量多 就会报错
for循坏的机制:
for i in [1,2,3]: print(i)
使用while循坏+迭代器模拟for循坏(必须要掌握)
lst = [1,2,3] lst_iter = lst.__iter__() while True: try: i = lst_iter.__next__() print(i) except StopIteration: break
总结:
lterable :可迭代对象.内部包含__iter__()函数
lterator:迭代器.内部包含__iter__同时包含__next__().
迭代器的特点:
1.节省内存
2.惰性机制
3.不能反复,只能向下执行
我们可以把要迭代的内容当成子弹.然后呢.获取到迭代器__iter__(),就把子弹都装在弹夹中.
然后发射就是__next__()把每个子弹(元素)打出来.for循坏的时候.一开始的时候是__iter__().来获取迭代器.后面每次获取元素都是通过__next__()来完成的.当程序遇到StopIteration将结束循环.
经典题目收藏:
user_list=[ {"name": "alex", "hobby": "抽烟"}, {"name": "alex", "hobby": "喝酒"}, {"name": "alex", "hobby": "烫头"}, {"name": "wusir", "hobby": "喊麦"}, {"name": "wusir", "hobby": "街舞"}, {"name": "alex", "hobby": "泡吧"}, {"name":"太白", "hobby":"开车"} ] # [{"name": "alex", "hobby_list": ["抽烟","喝酒","烫头","泡吧"]},
{"name": "wusir", "hobby_list": ["喊麦", "街舞"]},] result = [] # {'name': 'alex', 'hobby_list': ['抽烟']} for user in user_list: # 1.判断是否在result里面存在了这个人, 如果存在. 把hobby_list添加一个hobby # 2.不存在. 创建一个新字典 for new_user in result: if user['name'] == new_user['name']: new_user['hobby_list'].append(user['hobby']) break else: dic = {} dic["name"] = user['name'] dic['hobby_list'] = [user['hobby']] result.append(dic) print(result)
乘法口诀9*9 代码题
# 9*9 a = 1 while a <=9: b = 1 while b <= a: print("%dx%d=%d " % (a, b, a*b), end="") b = b + 1 print() # 换行 a = a + 1
# 接收n个参数. 返回最大值和最小值(字典) def func(*args): m = args[0] # 假设第0项就是最大值 mi = args[0] for el in args: if el > m: m = el # 当前这个元素比假设的那个大. 记录当前这个比较大的数 if el < mi: mi = el return {"最大值":m, "最小值":mi}