|
|
|
@ -1093,6 +1093,103 @@ Julio
|
|
|
|
|
</section> |
|
|
|
|
</section> |
|
|
|
|
|
|
|
|
|
<section> |
|
|
|
|
<section> |
|
|
|
|
<h3>Comprehensions e Generators</h3> |
|
|
|
|
|
|
|
|
|
<p>Python permite criar listas processando listas sem |
|
|
|
|
<code>for</code> com <i>list |
|
|
|
|
comprehensions</i>.</p> |
|
|
|
|
|
|
|
|
|
<pre><code class="hljs"> |
|
|
|
|
>>> a = [1, 2, 3] |
|
|
|
|
>>> [item * 2 for item in a] |
|
|
|
|
>>> [2, 4, 6] |
|
|
|
|
</code></pre> |
|
|
|
|
|
|
|
|
|
<p>Pra quem gosta de coisas "funcionais", é o mesmo que |
|
|
|
|
<code>map</code>.</p> |
|
|
|
|
|
|
|
|
|
<pre><code class="hljs"> |
|
|
|
|
>>> a = [1, 2, 3] |
|
|
|
|
>>> map(lamba f: f * 2, a) |
|
|
|
|
>>> [2, 4, 6] |
|
|
|
|
</code></pre> |
|
|
|
|
</section> |
|
|
|
|
|
|
|
|
|
<section> |
|
|
|
|
<h4>Comprehensions (contd.)</h4> |
|
|
|
|
<p>É possível filtrar elementos com list comprehensions.</p> |
|
|
|
|
|
|
|
|
|
<pre><code class="hljs"> |
|
|
|
|
>>> a = [1, 2, 3] |
|
|
|
|
>>> [item for item in a if item > 2] |
|
|
|
|
>>> [3] |
|
|
|
|
</code></pre> |
|
|
|
|
|
|
|
|
|
<p>Funcionalmente, é o mesmo que <code>filter</code>.</p> |
|
|
|
|
|
|
|
|
|
<pre><code class="hljs"> |
|
|
|
|
>>> a = [1, 2, 3] |
|
|
|
|
>>> filter(lambda f: f > 2, a) |
|
|
|
|
>>> [3] |
|
|
|
|
</code></pre> |
|
|
|
|
</section> |
|
|
|
|
|
|
|
|
|
<section> |
|
|
|
|
<h4>Generators</h4> |
|
|
|
|
|
|
|
|
|
<p>Enquanto que comprehensions criam novas listas, generators |
|
|
|
|
geram elementos sob demanda.</p> |
|
|
|
|
|
|
|
|
|
<pre><code class="hljs"> |
|
|
|
|
>>> a = [1, 2, 3] |
|
|
|
|
>>> (item * 2 for item in a) |
|
|
|
|
<generator object <genexpr> at 0x7f8673dfc050> |
|
|
|
|
</code></pre> |
|
|
|
|
</section> |
|
|
|
|
|
|
|
|
|
<section> |
|
|
|
|
<h5>Generators (contd.)</h5> |
|
|
|
|
|
|
|
|
|
<pre><code class="hljs"> |
|
|
|
|
>>> [item for item in range(5000000)] |
|
|
|
|
</code></pre> |
|
|
|
|
|
|
|
|
|
<p>vs</p> |
|
|
|
|
|
|
|
|
|
<pre><code class="hljs"> |
|
|
|
|
>>> (item for item in xrange(5000000)) |
|
|
|
|
</code></pre> |
|
|
|
|
</section> |
|
|
|
|
|
|
|
|
|
<section> |
|
|
|
|
<h5>Generators (contd.)</h5> |
|
|
|
|
|
|
|
|
|
<pre><code class="hljs"> |
|
|
|
|
>>> [item for item in range(5000000)][:5] |
|
|
|
|
</code></pre> |
|
|
|
|
|
|
|
|
|
<p>vs</p> |
|
|
|
|
|
|
|
|
|
<pre><code class="hljs"> |
|
|
|
|
>>> (item for item in xrange(5000000))[:5] |
|
|
|
|
</code></pre> |
|
|
|
|
</section> |
|
|
|
|
|
|
|
|
|
<section> |
|
|
|
|
<h5>Generators (contd.)</h5> |
|
|
|
|
|
|
|
|
|
<pre><code class="hljs"> |
|
|
|
|
>>> def gen(max_value): |
|
|
|
|
>>> for value in xrange(max_value): |
|
|
|
|
>>> yield value * 2 |
|
|
|
|
</code></pre> |
|
|
|
|
|
|
|
|
|
<p>Generator functions não podem ter <code>return</code>!</p> |
|
|
|
|
</section> |
|
|
|
|
</section> |
|
|
|
|
|
|
|
|
|
<section data-background='_images/thats-all-folks.jpg'> |
|
|
|
|
<section></section> |
|
|
|
|
</section> |
|
|
|
|