How do I find a value relative to where a list occurs within my list in Python?
<p>I have a list of numbers:</p>

<pre><code>Data = [0,2,0,1,2,1,0,2,0,2,0,1,2,0,2,1,1,...]
</code></pre>

<p>And I have a list of tuples of two, which is all possible combinations of the individual numbers above:</p>

<pre><code>Combinations = [(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)]
</code></pre>

<p>I want to try to find where each item in Combinations appears in Data and add the value after each occurrence to another list.</p>

<p>For example, for (0,2) I want to make a list [0,0,0,1] because those are the the values that fall immediately after (0,2) occurs in Data.</p>

<p>So far, I have:</p>

<pre><code>any(Data[i:i+len(CurrentTuple)] == CurrentTuple for i in xrange(len(Data)-len(CurrentTuple)+1))
</code></pre>

<p>Where <code>CurrentTuple</code> is <code>Combinations.pop()</code>. 
The problem is that this only gives me a Boolean of whether the <code>CurrentTuple</code> occurs in Data. What I really need is the value after each occurrence in Data.</p>

<p>Does anyone have any ideas as to how this can be solved? Thanks!</p>

<pre><code>sum([all(x) for x in (Data[i:i+len(CurrentTuple)] == CurrentTuple for i in xrange
(len(Data)-len(CurrentTuple)+1))])
</code></pre>

<p>What you did return a generator that produce the following list:</p>

<pre><code>[array([False,  True], dtype=bool),
 array([ True, False], dtype=bool),
 array([False,  True], dtype=bool),
 ...
 array([False, False], dtype=bool),
 array([False, False], dtype=bool),
 array([False, False], dtype=bool),
 array([False,  True], dtype=bool)]
</code></pre>

<p>One of the array that you have in this list match the <code>CurrentTuple</code> only if both the <code>bool</code> in the array are <code>True</code>. The <code>all</code> return <code>True</code> only if all the elements of the list are <code>True</code> so the list generated by the <code>[all(x) for x in ...]</code> will contains <code>True</code> only if the twin of numbers match the <code>CurrentTuple</code>. A <code>True</code> is conted as <code>1</code> when you use <code>sum</code>. I hope it is clear. </p>

<p>If you want to compare only non-overlapping pairs:</p>

<pre><code>[2,2,
 0,2,
 ...]
</code></pre>

<p>and keep the algorithm as general as possible, you can use the following:</p>

<pre><code>sum([all(x) for x in (Data[i:i+len(CurrentTuple)] == CurrentTuple for i in xrange
(0,len(Data)-len(CurrentTuple)+1,len(CurrentTuple)))])
</code></pre>

<p>Despite much more cryptic, this code is much faster than any alternative that using <code>append</code> (look [<a href="http://stackoverflow.com/questions/39518899/3-array-generators-faster-than-1-for-loop/39519661#39519661]">3 array generators faster than 1 for loop</a> to understand why).</p>

python list tuples markov-chains