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>It works, except you forgot to replace <code>countsminusone</code> by <code>countsminusone1</code> in your last line.</p>

<pre><code>countsminusone1 = [[1 if x &lt;= 0 else x for x in pair] for pair in countsminusone]
Divide = [[n/d for n, d in zip(subq, subr)] for subq, subr in zip(counts, countsminusone1)]
</code></pre>

python list replace list-comprehension value