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>I think you are making this much too complicated. Let's state what you actually want to do in the simplest way:</p>

<blockquote>
  <p>GOAL: Divide every number n in list of lists by n - 1 or, if n - 1 &lt;= 0, by 1.</p>
</blockquote>

<p>This can be done without creating extra lists and zipping:</p>

<pre><code>counts = [[2, 2, 2, 0], [2, 2, 1, 0]]
divided = [[i / max(i - 1, 1) for i in sublst] for sublst in counts]
</code></pre>

<p>Note that in this case, <code>max(i - 1, 1)</code> will <em>always</em> be 1.</p>

python list replace list-comprehension value