Table of Contents
回复内容:
Home Backend Development Python Tutorial 使用yield可以做哪些很酷的事情?

使用yield可以做哪些很酷的事情?

Jun 06, 2016 pm 04:23 PM
javascript python yield

使用生成器(Generator)和yield可以做哪些有趣的、酷酷的、让人意想不到的事情?
不限编程语言,例如python、JavaScript 等。

回复内容:

yield 在 JavaScript 中用的最多的可能就是结合 Promise/Thunk 等实现异步操作,比如大名鼎鼎的 tj/co · GitHub,所以已经不是「让人意想不到」的东西了。
理解 Generator 的特性后,实现一个玩具版的 co 还是很简单的:
function async(generator) {
  return new Promise(function(resolve, reject) {
    var g = generator()

    function next(val) {
      var result = g.next(val)
      var value = result.value

      if (!result.done) {
        value.then(next).catch(reject)
      }
      else {
        resolve(value)
      }
    }

    next()
  })
}
Copy after login
最典型的不就是async/await么?


不了解yield怎么实现async/await的,用C#代码试举一例:

IEnumerable<Action<Action>> SomeAsyncMethod()
{
  //blabla
  yield return await( asyncMethod, context );

  //blabla
  yield return await( asyncMethod, context );

  //blabla
}
Copy after login
可以做动画呀,效果如图:
<span class="c"># -*- coding: utf-8 -*-</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="kn">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="kn">as</span> <span class="nn">plt</span>
<span class="kn">import</span> <span class="nn">matplotlib.animation</span> <span class="kn">as</span> <span class="nn">animation</span>
<span class="kn">import</span> <span class="nn">math</span><span class="o">,</span> <span class="nn">random</span>
<span class="c"># 需要安装的库:Numpy和Matplotlib,推荐直接Anaconda</span>
<span class="n">fig</span><span class="p">,</span> <span class="n">axes1</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">subplots</span><span class="p">()</span>
<span class="c"># 设置坐标轴长度</span>
<span class="n">axes1</span><span class="o">.</span><span class="n">set_ylim</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mf">1.4</span><span class="p">)</span>
<span class="n">axes1</span><span class="o">.</span><span class="n">set_xlim</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="o">*</span><span class="n">np</span><span class="o">.</span><span class="n">pi</span><span class="o">/</span><span class="mf">0.01</span><span class="p">)</span>
<span class="c"># 设置初始x、y数值数组</span>
<span class="n">xdata</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">2</span><span class="o">*</span><span class="n">np</span><span class="o">.</span><span class="n">pi</span><span class="p">,</span> <span class="mf">0.01</span><span class="p">)</span>
<span class="n">ydata</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sin</span><span class="p">(</span><span class="n">xdata</span><span class="p">)</span>
<span class="c"># 获得线条</span>
<span class="n">line</span><span class="p">,</span> <span class="o">=</span> <span class="n">axes1</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">xdata</span><span class="p">)</span>
<span class="c"># 毛刺倍率,从0开始增长,offset越大毛刺越大</span>
<span class="n">offset</span> <span class="o">=</span> <span class="mf">0.0</span>

<span class="c">#因为update的参数是调用函数data_gen,所以第一个默认参数不能是framenum</span>
<span class="k">def</span> <span class="nf">update</span><span class="p">(</span><span class="n">data</span><span class="p">):</span>
    <span class="k">global</span> <span class="n">offset</span>
    <span class="n">line</span><span class="o">.</span><span class="n">set_ydata</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">line</span><span class="p">,</span>
<span class="c"># 每次生成10个随机数据</span>
<span class="c"># 每次变化整幅图的话,yield一个整图就行了</span>
<span class="k">def</span> <span class="nf">data_gen</span><span class="p">():</span>
    <span class="k">global</span> <span class="n">offset</span>
    <span class="k">while</span> <span class="bp">True</span><span class="p">:</span>
        <span class="n">length</span> <span class="o">=</span> <span class="nb">float</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">xdata</span><span class="p">))</span>
        <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">xdata</span><span class="p">)):</span>
            <span class="n">ydata</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="o">=</span><span class="n">math</span><span class="o">.</span><span class="n">sin</span><span class="p">(</span><span class="n">xdata</span><span class="p">[</span><span class="n">i</span><span class="p">])</span><span class="o">+</span><span class="mf">0.2</span>
            <span class="k">if</span> <span class="n">i</span><span class="o">></span><span class="n">length</span><span class="o">/</span><span class="mf">18.0</span> <span class="ow">and</span> <span class="n">i</span><span class="o"><</span><span class="p">(</span><span class="n">length</span><span class="o">*</span><span class="mf">2.7</span><span class="o">/</span><span class="mf">6.0</span><span class="p">):</span>
                <span class="n">ydata</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="o">+=</span><span class="n">offset</span><span class="o">*</span><span class="p">(</span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">()</span><span class="o">-</span><span class="mf">0.5</span><span class="p">)</span>
        <span class="n">offset</span> <span class="o">+=</span> <span class="mf">0.05</span>
        <span class="c">#可以设置offset的最大值</span>
        <span class="k">if</span> <span class="n">offset</span><span class="o">>=</span><span class="mf">0.5</span><span class="p">:</span>
           <span class="n">offset</span><span class="o">=</span><span class="mf">0.0</span>
        <span class="k">yield</span> <span class="n">ydata</span>
<span class="c"># 配置完毕,开始播放</span>
<span class="n">ani</span> <span class="o">=</span> <span class="n">animation</span><span class="o">.</span><span class="n">FuncAnimation</span><span class="p">(</span><span class="n">fig</span><span class="p">,</span> <span class="n">update</span><span class="p">,</span> <span class="n">data_gen</span><span class="p">,</span> <span class="n">interval</span><span class="o">=</span><span class="mi">800</span><span class="p">,</span> <span class="n">repeat</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
Copy after login
模拟离散事件,还有更简洁优雅的方式么

Overview — SimPy 3.0.8 documentation 这个问题就是给我准备的嘛

当有人声称在CPython里实现了一个沙盒的时候就可以用yield去逗他了,I was looking through the code and saw someone submitted this but didn't run it:...

酷到没工作... A Curious Course on Coroutines and Concurrency 可以写出一个并发的库
Generator Tricks for Systems Programmers 可以写个流处理框架 参见David Beazley大神几次PyCon的pdf,看完我简直是惊呆了。dabeaz.com 可以用来训练神经网络.
比如Lasagne/Lasagne · GitHub 中的一段示例代码:
<span class="k">def</span> <span class="nf">train</span><span class="p">(</span><span class="n">iter_funcs</span><span class="p">,</span> <span class="n">dataset</span><span class="p">,</span> <span class="n">batch_size</span><span class="o">=</span><span class="n">BATCH_SIZE</span><span class="p">):</span>
    <span class="sd">"""Train the model with `dataset` with mini-batch training. Each</span>
<span class="sd">       mini-batch has `batch_size` recordings.</span>
<span class="sd">    """</span>
    <span class="n">num_batches_train</span> <span class="o">=</span> <span class="n">dataset</span><span class="p">[</span><span class="s">'num_examples_train'</span><span class="p">]</span> <span class="o">//</span> <span class="n">batch_size</span>
    <span class="n">num_batches_valid</span> <span class="o">=</span> <span class="n">dataset</span><span class="p">[</span><span class="s">'num_examples_valid'</span><span class="p">]</span> <span class="o">//</span> <span class="n">batch_size</span>

    <span class="k">for</span> <span class="n">epoch</span> <span class="ow">in</span> <span class="n">itertools</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="mi">1</span><span class="p">):</span>
        <span class="n">batch_train_losses</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">for</span> <span class="n">b</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">num_batches_train</span><span class="p">):</span>
            <span class="n">batch_train_loss</span> <span class="o">=</span> <span class="n">iter_funcs</span><span class="p">[</span><span class="s">'train'</span><span class="p">](</span><span class="n">b</span><span class="p">)</span>
            <span class="n">batch_train_losses</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">batch_train_loss</span><span class="p">)</span>

        <span class="n">avg_train_loss</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span><span class="n">batch_train_losses</span><span class="p">)</span>

        <span class="n">batch_valid_losses</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="n">batch_valid_accuracies</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">for</span> <span class="n">b</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">num_batches_valid</span><span class="p">):</span>
            <span class="n">batch_valid_loss</span><span class="p">,</span> <span class="n">batch_valid_accuracy</span> <span class="o">=</span> <span class="n">iter_funcs</span><span class="p">[</span><span class="s">'valid'</span><span class="p">](</span><span class="n">b</span><span class="p">)</span>
            <span class="n">batch_valid_losses</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">batch_valid_loss</span><span class="p">)</span>
            <span class="n">batch_valid_accuracies</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">batch_valid_accuracy</span><span class="p">)</span>

        <span class="n">avg_valid_loss</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span><span class="n">batch_valid_losses</span><span class="p">)</span>
        <span class="n">avg_valid_accuracy</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span><span class="n">batch_valid_accuracies</span><span class="p">)</span>

        <span class="k">yield</span> <span class="p">{</span>
            <span class="s">'number'</span><span class="p">:</span> <span class="n">epoch</span><span class="p">,</span>
            <span class="s">'train_loss'</span><span class="p">:</span> <span class="n">avg_train_loss</span><span class="p">,</span>
            <span class="s">'valid_loss'</span><span class="p">:</span> <span class="n">avg_valid_loss</span><span class="p">,</span>
            <span class="s">'valid_accuracy'</span><span class="p">:</span> <span class="n">avg_valid_accuracy</span><span class="p">,</span>
        <span class="p">}</span>
Copy after login
tornado就是使用generator实现的协程(coroutine)模型,再配合event loop实现高并发的 使用迭代器遍历二叉树。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

Is the conversion speed fast when converting XML to PDF on mobile phone? Is the conversion speed fast when converting XML to PDF on mobile phone? Apr 02, 2025 pm 10:09 PM

The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

How to convert XML files to PDF on your phone? How to convert XML files to PDF on your phone? Apr 02, 2025 pm 10:12 PM

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

Is there any mobile app that can convert XML into PDF? Is there any mobile app that can convert XML into PDF? Apr 02, 2025 pm 08:54 PM

An application that converts XML directly to PDF cannot be found because they are two fundamentally different formats. XML is used to store data, while PDF is used to display documents. To complete the transformation, you can use programming languages ​​and libraries such as Python and ReportLab to parse XML data and generate PDF documents.

How to convert xml into pictures How to convert xml into pictures Apr 03, 2025 am 07:39 AM

XML can be converted to images by using an XSLT converter or image library. XSLT Converter: Use an XSLT processor and stylesheet to convert XML to images. Image Library: Use libraries such as PIL or ImageMagick to create images from XML data, such as drawing shapes and text.

How to control the size of XML converted to images? How to control the size of XML converted to images? Apr 02, 2025 pm 07:24 PM

To generate images through XML, you need to use graph libraries (such as Pillow and JFreeChart) as bridges to generate images based on metadata (size, color) in XML. The key to controlling the size of the image is to adjust the values ​​of the &lt;width&gt; and &lt;height&gt; tags in XML. However, in practical applications, the complexity of XML structure, the fineness of graph drawing, the speed of image generation and memory consumption, and the selection of image formats all have an impact on the generated image size. Therefore, it is necessary to have a deep understanding of XML structure, proficient in the graphics library, and consider factors such as optimization algorithms and image format selection.

Recommended XML formatting tool Recommended XML formatting tool Apr 02, 2025 pm 09:03 PM

XML formatting tools can type code according to rules to improve readability and understanding. When selecting a tool, pay attention to customization capabilities, handling of special circumstances, performance and ease of use. Commonly used tool types include online tools, IDE plug-ins, and command-line tools.

How to open xml format How to open xml format Apr 02, 2025 pm 09:00 PM

Use most text editors to open XML files; if you need a more intuitive tree display, you can use an XML editor, such as Oxygen XML Editor or XMLSpy; if you process XML data in a program, you need to use a programming language (such as Python) and XML libraries (such as xml.etree.ElementTree) to parse.

See all articles