Filling a diagonal matrix based on selectors
<p>I have two lists:</p>

<pre><code>[(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2)]

[False, False, True, False, False, False]
</code></pre>

<p>The first list represent the row_number, column_number of the matrix. The second list represent the element value. How can I create an efficient loop(or other algorithm) so I end up with a 4 by 4 matrix:</p>

<pre><code>0 0 0 0
0 0 0 0
0 1 0 0
0 0 0 0 
</code></pre>

<p>This is actually pretty easy if you use <a href="https://docs.python.org/3.6/library/itertools.html#itertools.compress" rel="nofollow"><code>itertools.compress</code></a>:</p>

<pre><code>from itertools import compress

d = [(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2)]   
sel = [False, False, True, False, False, False]

res = [[0 if (j, i) not in compress(d, sel) else 1 for i in range(4)] for j in range(4)]
</code></pre>

<p>Yields:</p>

<pre><code>[[0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0]]
</code></pre>

<p>Compress takes some data (<code>d</code> here) and some selectors (<code>sel</code> here) and retains the data that has the corresponding selector with a true value. </p>

<p>The list comprehension then creates the matrix and fills it with zeros or ones accordingly.</p>

python python-3.x