Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Just iterate over pairs, using <code>zip()</code>, which is much more readable.</p> <p><strong>UPDATE:</strong> for python 2.x, use <code>itertools.izip</code> instead as it is more efficient!</p> <pre><code>from itertools import izip for prev, next in izip(tmp, tmp[1:]): print 'seq: ', next[1], 'prev seq:', prev[1], 'variance: ', next[1]-prev[1] </code></pre> <p>which can also use value unpacking to avoid the index:</p> <pre><code>for (_, prev), (_, next) in izip(tmp, tmp[1:]): print 'seq: ', next, 'prev seq:', prev, 'variance: ', next-prev </code></pre> <p>Or, if you really need the first iteration too</p> <pre><code>for prev, next in izip(tmp, tmp[:1] + tmp): print 'seq: ', next[1], 'prev seq:', prev[1], 'variance: ', next[1]-prev[1] </code></pre> <p><strong>EDIT</strong></p> <p>If you want to avoid the creation of a list in the second argument you can also use an explicit iterator:</p> <pre><code>itr = iter(tmp) itr.next() # here I assume tmp is not empty, otherwise an exception will be thrown for prev, next in izip(tmp, itr): print 'seq: ', next[1], 'prev seq:', prev[1], 'variance: ', next[1]-prev[1] </code></pre> <p><em>Note</em>: This zip pattern is useful in similar problems too. For example to extract successive triplets from a list:</p> <pre><code>xs = range(9) triplets = zip(xs[::3], xs[1::3], xs[2::3]) # python 2.x, zip returns a list print xs # [0, 1, 2, 3, 4, 5, 6, 7, 8] print triplets # [(0, 1, 2), (3, 4, 5), (6, 7, 8)] </code></pre> <p>Also note that in <a href="http://diveintopython3.org/porting-code-to-python-3-with-2to3.html#zip" rel="nofollow noreferrer">python 3 zip returns an iterator</a>, similar to <code>itertools.izip</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload