Reputation: 9389
I'm working in a 2D matrix with a simple polynomial algorithm:
for i in range(len(content1)):
for j in range(len(content2)):
if content1[i]==content2[j]:
matrix[i][j]=1
else:
matrix[i][j]=0
This code itself do not compile for a simple reason. dot_matrix is not initialized. So what is the easier way to do that?
Also, how could I implement the same logic I'm using above in a one lined code like this:
matrix = [[0 for x in range(len(content1))] for x in range(len(content2))]
Upvotes: 2
Views: 85
Reputation: 235
For one thing, you're using content1 as the outer index in the first chunck of code, so matric should be initialized with content1 on the outer as well:
matrix = [[0 for x in range(len(content2))] for x in range(len(content1))]
And yes, you can do it in one line like the other answer mentions:
matrix = [[1 if i == j else 0 for j in content2] for i in content1]
Upvotes: 2
Reputation: 2011
Replace the x
s with i
and j
, then replace the 0
with (1 if content1[i]==content2[j] else 0)
.
Upvotes: 1