How to replace elements by value in a list of lists in Python?
<p>I have:</p>

<pre><code> counts = [[2, 2, 2, 0], [2, 2, 1, 0]]
 countsminusone = [[1, 1, 1, -1], [1, 1, 0, -1]] #Which is counts - 1
</code></pre>

<p>For every value, where countsminusone is 0 or less than 0, I want to replace it with 1.</p>

<pre><code> countsminusone1 = [[1 if x == 0 or x &lt; 0 else x for x in pair] for pair in countsminusone] #I cannot get this to work
</code></pre>

<p>And then divide counts by countsminusone</p>

<pre><code>Divide = [[n/d for n, d in zip(subq, subr)] for subq, subr in zip(counts, countsminusone)] #This should work if the above works
</code></pre>

<p>This works for any number of elements inside the sub list</p>

<pre><code>import numpy as np
map( list , np.array(counts)/np.array(zip(*([ iter([ 1 if i &lt;=0 else i for i in sum( countsminusone , []) ]) ] * len(countsminusone[0]) ) ) ) )
</code></pre>

python list replace list-comprehension value