十三. Python基础(13)--生成器进阶
十三. Python基础(13)--生成器进阶
1 ● send()方法
2 ● send()函数的简单案例
|
def fun(): print('*') value = yield 1 print('**', value) yield 2
g = fun() print(g.__next__()) # print(g.__next__()) # ** None print(g.send("aaa")) # ** aaa # print(g.send("bbb")) # 警示"StopIteration"异常, 因为此时"bbb"没有可以用来赋值的的yield表达式 ''' * 1 ** aaa 2 ''' |
|
# send()和__next__()工作的起始位置是完全相同的 # send()可以把一个值作为信号量(semaphore)传到函数中去 # 在生成器执行伊始, 只能先用__next__()或send(None), 因为用send()传递非None参数的时候,在生成器中必须有一个未被赋值的yield表达式 # __next_()方法以及send()方法的数量 不同多于 yield表达式的数量, 否则警示异常StopIteration. |
3 ● 计算累计平均数
|
def wrapper(func): # 这个装饰器中只做一件事:g.__next__; 或者next(g), 也就是激活生成器(next是内置函数) def inner(*args, **kwargs): g = func(*args, **kwargs) # 最好不要跟外面的创建的gen生成器重名 g.__next__() # 也可以是g.send(None), 用来激活生成器 return g return inner
@wrapper def average_func(): total = 0 count = 0 average = 0 while True: # 这个while True可以让使用者一直使用send方法, 也就是调用这个函数的可生成一个取之不尽用之不竭的生成器, 注意这里不会造成死循环 value = yield average total += value count += 1 average = total/count
gen = average_func() print(gen.send(30)) print(gen.send(50)) print(gen.send(10)) |
|
''' 30.0 40.0 30.0 ''' |
4 ● 列表推导式/字典推导式/集合推导式(没有元组推导式)
|
列表推导式: for i in range(0, 21, 2) |
|
字典推导式: 案例①: dic = {'k1':'v1', 'k2':'v2'} print({dic[key]: key # {'v1': 'k1', 'v2': 'k2'}
案例②: dic = {'a': 10, 'b': 34, 'A': 7, 'Z': 3} dic_new = {k.lower(): dic.get(k.lower(), 0) + dic.get(k.upper(), 0) print(dic_new) # {'a': 17, 'b': 34, 'z': 3} |
|
集合推导式: (自带去重的功能) print({i**2 for i in [1, -1, 2]}) # {1, 4} |
5 ● 生成器表达式
|
把列表解析的[]换成()得到的就是生成器表达式. |
|
gen_list = (i**2 for i in range(0, 21, 2) if i < 11) for i in gen_list: print(i) ''' 0 4 16 36 64 100 ''' |
|
dic = {'k1':'v1', 'k2':'v2'} gen_a = (key for key in dic) gen_b = (key for key in dic.items()) for i in gen_a: print(i) for i in gen_b: print(i) ''' k1 k2 ('k1', 'v1') ('k2', 'v2') ''' |
|
gen_col = (i**2 for i in {1, -1, 2}) for i in gen_col: print(i) ''' 1 4 1 ''' |
6 ● 面试题1
|
def demo(): for i in range(4): yield i
g=demo()
g1=(i for i in g) g2=(i for i in g1)
print(list(g1)) # [0, 1, 2, 3] print(list(g2)) # [] |
7 ● 面试题2
|
def add(n,i): return n+i
def test(): for i in range(4): yield i
g=test() for n in [1,10]: g=(add(n,i) for i in g) # 生成器推导式 print(list(g))
# [1, 2, 3, 4] # []注意这一步是没有数跟10相加, 因此为空. |
|
def add(n,i): return n+i
def test(): for i in range(4): yield i
g=test() for n in [1,10]: g=(add(n,i) for i in g)
print(list(g))
''' ① 上面的三个g是三个不同的迭代器 ② 上面一段相当于: n = 1 g=(add(1,i) for i in range(4)) # 1+0+1+2+3=7 # 生成器中的数据没有被获取, 因为生成器只有在被调用的时候才会生成相应的数据(用__next__()、 for、list调用, 或被其它函数调用), 反之就不会生成--惰性运算. n = 10 g=(add(n,i) for i in g) print(list(g)) '''
# [20, 21, 22, 23] |
|
如果这里是: n=1 g=(add(n,i) for i in g) # 生成器推导式 n=10 g=(add(n,i) for i in g) n=5 g=(add(n,i) for i in g) print(list(g))
那么相当于运行: for n in [1,10,5]: g=(add(n,i) for i in g) # 生成器推导式 print(list(g))
即: n=1 g = (add(n,i) for i in g) n=10 g = (add(n,i) for i in (add(n,i) for i in g)) n=5 g = (add(5,i) for i in add(n,i) for i in (add(n,i) for i in g))
# [15, 16, 17, 18] |
十三. Python基础(13)--生成器进阶的更多相关文章
- 十二. Python基础(12)--生成器
十二. Python基础(12)--生成器 1 ● 可迭代对象(iterable) An object capable of returning its members one at a time. ...
- 二十三. Python基础(23)--经典类和新式类
二十三. Python基础(23)--经典类和新式类 ●知识框架 ●接口类&抽象类的实现 # 接口类&抽象类的实现 #①抛出异常法 class Parent(object): ...
- python基础篇之进阶
python基础篇之进阶 参考博客:http://www.cnblogs.com/wupeiqi/articles/5115190.html python种类 1. cpython 使用c解释器生产 ...
- (转)python基础学习-----生成器和迭代器
在Python中,很多对象都是可以通过for语句来直接遍历的,例如list.string.dict等等,这些对象都可以被称为可迭代对象.至于说哪些对象是可以被迭代访问的,就要了解一下迭代器相关的知识了 ...
- Python全栈开发之路 【第五篇】:Python基础之函数进阶(装饰器、生成器&迭代器)
本节内容 一.名称空间 又名name space,就是存放名字的地方.举例说明,若变量x=1,1存放于内存中,那名字x存放在哪里呢?名称空间正是存放名字x与1绑定关系的地方. 名称空间共3种,分别如下 ...
- Python基础—面向对象(进阶篇)
通过上一篇博客我们已经对面向对象有所了解,下面我们先回顾一下上篇文章介绍的内容: 上篇博客地址:http://www.cnblogs.com/phennry/p/5606718.html 面向对象是一 ...
- Python基础之生成器、迭代器
一.字符串格式化进阶 Python的字符串格式化有两种方式: 百分号方式.format方式,由于百分号的方式相对来说比较老,在社区里讨论format方式有望取代百分号方式,下面我们分别介绍一下这两种方 ...
- Python之路,Day8 - Python基础 面向对象高级进阶与socket基础
类的成员 类的成员可以分为三大类:字段.方法和属性 注:所有成员中,只有普通字段的内容保存对象中,即:根据此类创建了多少对象,在内存中就有多少个普通字段.而其他的成员,则都是保存在类中,即:无论对象的 ...
- Python之路【第六篇】python基础 之面向对象进阶
一 isinstance(obj,cls)和issubclass(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls 的对象 和 issubclass(su ...
随机推荐
- lumerical中DEVICE和MODE模块的交互使用(真的很干货!!可以自信的说网上绝对找不到比我更详细的步骤了)
几个脚本文件很重要! Lumerical仿真流程: 一.DEVICE: (1).建模并且运行完之后,在脚本提示符下键入以下脚本行以运行plotDopingProfile.lsf如图1(文件名如果索引不 ...
- C#给整个panel添加点击事件的方法
首先要明白两点: panel直接添加点击事件无效 panel添加透明按钮覆盖无法实现 那么方法就是 在panel上添加pictureBox 设置 //充满整个panel pictureBox1.Doc ...
- 解释变量(Explanatory Variable)
转自:http://www.statisticshowto.com/explanatory-variable/ What is an Explanatory Variable? An explanat ...
- No address associated with hostname
java.net.UnknownHostException: Unable to resolve host "www.baidu.com": No address associat ...
- DAG最长路问题 hdu-1224
用DFS+记忆化写了一下,拓扑排序+DP的我还没弄明白.据说Codeforces 721C就是这类题目,因为有费用限制,DFS不太好写,有时间把DP法想明白来. #include <iostre ...
- android ------ Emulator: error: x86 emulation currently requires hardware acceleration
我创建 Android 模拟器,运行项目时出现了一个这样的错误: 如下: emulator ERROR:x86 emulation currently requires hardware accele ...
- use . adb . get wifi
adb shell 连接手机获取root权限,如果返回的字符串中不包含root字样,再输入su命令回车 继续输入cat /data/misc/wifi/*.conf命令,将会把文件打印出来 ssid表 ...
- Roman To Integer leetcode java
问题描述: Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range fr ...
- 『C++』基础知识点
一.基础知识 1.C++编译流程 以Unix系统编译中间文件为说明: .cpp—(编译预处理)—>.ii—(编译)—>.s—(汇编)—>.o—(ld,连接)—>.out 2.# ...
- vivado第一天从建立文件运行小程序开始
今天,是第一天什么也处于懵懂的时候,首要的任务就是建立一个文件 首先打开vivado运行软件, 如图所示,选择第一个create new project 来新建文件 选择存储路径,一路向下 当选择芯片 ...