Reputation: 1223
I have 2D matrix and I want to fill it with 0 and 1. And I have a list include some value.
For example:
values = [1, 3, 5, 8]
and I want to create this matrix
matrix = [[0, 1, 0],
[1, 0, 1],
[0, 0, 1]]
I made this with two nested for loop witf if statement. Values is random integers from 0 to 100. And my matrix will be 10*10. Is there any way to create this more elegant?
Upvotes: 3
Views: 32767
Reputation: 10565
You can use a list compreehension:
[[1 if i*10+j in values else 0 for j in range(10)] for i in range(10)]
In this case, I suggest you to create values
as a set.
values = set([1, 3, 5, 8])
Upvotes: 2
Reputation: 25528
If you can use NumPy, use fancy indexing into a flattened view of the array and reshape:
In [1]: import numpy as np
In [2]: a = np.zeros(9)
In [3]: a
Out[3]: array([ 0., 0., 0., 0., 0., 0., 0., 0., 0.])
In [4]: values = [1,3,5,8]
In [5]: a[values] = 1
In [6]: a
Out[6]: array([ 0., 1., 0., 1., 0., 1., 0., 0., 1.])
In [7]: a.reshape((3,3))
Out[7]:
array([[ 0., 1., 0.],
[ 1., 0., 1.],
[ 0., 0., 1.]])
If you want an integer array, declare a
as a = np.zeros(9, dtype=int)
.
Upvotes: 8