Python yield与实现教程分享

简介: Python yield与实现教程分享

基本操作

通过yield来创建生成器

def func():
for i in xrange(10);
yield i

通过列表来创建生成器

[i for i in xrange(10)]

调用如下

f = func()
f # 此时生成器还没有运行


f.next() # 当i=0时,遇到yield关键字,直接返回
0
f.next() # 继续上一次执行的位置,进入下一层循环
1
...
f.next()
9
f.next() # 当执行完最后一次循环后,结束yield语句,生成StopIteration异常
Traceback (most recent call last):
File "", line 1, in
StopIteration

除了next函数,生成器还支持send函数。该函数可以向生成器传递参数。

def func():
... n = 0
... while 1:
... n = yield n #可以通过send函数向n赋值
//代码效果参考:https://v.youku.com/v_show/id_XNjQwMDM2NzA4NA==.html

...

f = func()
f.next() # 默认情况下n为0
0
f.send(1) #n赋值1
1
f.send(2)
2

应用
最经典的例子,生成无限序列。

常规的解决方法是,生成一个满足要求的很大的列表,这个列表需要保存在内存中,很明显内存限制了这个问题。

def get_primes(start):
for element in magical_infinite_range(start):
if is_prime(element):
return element
如果使用生成器就不需要返回整个列表,每次都只是返回一个数据,避免了内存的限制问题。

def get_primes(number):
while True:
if is_prime(number):
yield number
number += 1
生成器源码分析
生成器的源码在Objects/genobject.c。

调用栈
在解释生成器之前,需要讲解一下Python虚拟机的调用原理。

Python虚拟机有一个栈帧的调用栈,其中栈帧的是PyFrameObject,位于Include/frameobject.h。

typedef struct _frame {
PyObject_VAR_HEAD
struct _frame f_back; / previous frame, or NULL /
PyCodeObject
f_code; / code segment /
PyObject f_builtins; / builtin symbol table (PyDictObject) */

//代码效果参考:https://v.youku.com/v_show/id_XNjQwMDM3NjA2NA==.html
PyObject f_globals; / global symbol table (PyDictObject) /
PyObject
f_locals; / local symbol table (any mapping) /
PyObject f_valuestack; / points after the last local /
/ Next free slot in f_valuestack. Frame creation sets to f_valuestack.
Frame evaluation usually NULLs it, but a frame that yields sets it
to the current stack top.
/
PyObject
f_stacktop;
PyObject f_trace; / Trace function */

/* If an exception is raised in this frame, the next three are used to
 * record the exception info (if any) originally in the thread state.  See
 * comments before set_exc_info() -- it's not obvious.
 * Invariant:  if _type is NULL, then so are _value and _traceback.
 * Desired invariant:  all three are NULL, or all three are non-NULL.  That
 * one isn't currently true, but "should be".
 */
PyObject *f_exc_type, *f_exc_value, *f_exc_traceback;

PyThreadState *f_tstate;
int f_lasti;        /* Last instruction if called */
/* Call PyFrame_GetLineNumber() instead of reading this field
   directly.  As of 2.3 f_lineno is only valid when tracing is
   active (i.e. when f_trace is set).  At other times we use
   PyCode_Addr2Line to calculate the line from the current
   bytecode index. */
int f_lineno;        /* Current line number */
int f_iblock;        /* index in f_blockstack */
PyTryBlock f_blockstack[CO_MAXBLOCKS]; /* for try and loop blocks */
PyObject *f_localsplus[1];    /* locals+stack, dynamically sized */

} PyFrameObject;
栈帧保存了给出代码的的信息和上下文,其中包含最后执行的指令,全局和局部命名空间,异常状态等信息。f_valueblock保存了数据,b_blockstack保存了异常和循环控制方法。

举一个例子来说明,

def foo():
x = 1
def bar(y):
z = y + 2 # <--- (3) ... and the interpreter is here.
return z
return bar(x) # <--- (2) ... which is returning a call to bar ...
foo() # <--- (1) We're in the middle of a call to foo ...

相关文章
|
1月前
|
数据可视化 DataX Python
Seaborn 教程-绘图函数
Seaborn 教程-绘图函数
70 8
|
1月前
Seaborn 教程-主题(Theme)
Seaborn 教程-主题(Theme)
119 7
|
1月前
|
Python
Seaborn 教程-模板(Context)
Seaborn 教程-模板(Context)
51 4
|
1月前
|
数据可视化 Python
Seaborn 教程
Seaborn 教程
50 5
|
2月前
|
Python
SciPy 教程 之 Scipy 显著性检验 9
SciPy 教程之 Scipy 显著性检验第9部分,介绍了显著性检验的基本概念、作用及原理,通过样本信息判断假设是否成立。着重讲解了使用scipy.stats模块进行显著性检验的方法,包括正态性检验中的偏度和峰度计算,以及如何利用normaltest()函数评估数据是否符合正态分布。示例代码展示了如何计算一组随机数的偏度和峰度。
35 1
|
2月前
|
BI Python
SciPy 教程 之 Scipy 显著性检验 8
本教程介绍SciPy中显著性检验的应用,包括如何利用scipy.stats模块进行显著性检验,以判断样本与总体假设间的差异是否显著。通过示例代码展示了如何使用describe()函数获取数组的统计描述信息,如观测次数、最小最大值、均值、方差等。
38 1
|
2月前
|
数据采集 数据可视化 数据挖掘
深入浅出:使用Python进行数据分析的基础教程
【10月更文挑战第41天】本文旨在为初学者提供一个关于如何使用Python语言进行数据分析的入门指南。我们将通过实际案例,了解数据处理的基本步骤,包括数据的导入、清洗、处理、分析和可视化。文章将用浅显易懂的语言,带领读者一步步掌握数据分析师的基本功,并在文末附上完整的代码示例供参考和实践。
|
2月前
|
Python
SciPy 教程 之 Scipy 显著性检验 6
显著性检验是统计学中用于判断样本与总体假设间是否存在显著差异的方法。SciPy的scipy.stats模块提供了执行显著性检验的工具,如T检验,用于比较两组数据的均值是否来自同一分布。通过ttest_ind()函数,可以获取两样本的t统计量和p值,进而判断差异是否显著。示例代码展示了如何使用该函数进行T检验并输出结果。
36 1
|
2月前
|
Python
SciPy 教程 之 Scipy 显著性检验 3
本教程介绍Scipy显著性检验,包括其基本概念、原理及应用。显著性检验用于判断样本与总体假设间的差异是否显著,是统计学中的重要工具。Scipy通过`scipy.stats`模块提供了相关功能,支持双边检验等方法。
46 1
|
2月前
|
机器学习/深度学习 Python
SciPy 教程 之 SciPy 插值 2
SciPy插值教程:介绍插值概念及其在数值分析中的应用,特别是在处理数据缺失时的插补和平滑数据集。SciPy的`scipy.interpolate`模块提供了强大的插值功能,如一维插值和样条插值。通过`UnivariateSpline()`函数,可以轻松实现单变量插值,示例代码展示了如何对非线性点进行插值计算。
35 3