Comparing multidimensional lists in Python

Question:

I have two multidimensional lists J,Cond. For every True element of Cond[0], I want the corresponding element in J[0] to be zero. I present the current and expected output.

J=[[0, 2, 0, 6, 7, 9, 10]]
Cond=[[False, True, False, True, True, True, True]]

for i in range(0,len(J[0])):
    if(Cond[0][i]==True):
        J[0][i]==0
print(J)

The current output is

[[0, 2, 0, 6, 7, 9, 10]]

The expected output is

[[0, 0, 0, 0, 0, 0, 0]]
Asked By: isaacmodi123

||

Answers:

Use J[0][i] = 0 instead of J[0][i] == 0.
Assignment is done by a single equal sign, while checking for equality is done by double equal sign.

Answered By: orimiles5

You have an operator error in the if condition. Here is the code for the same

J=[[0, 2, 0, 6, 7, 9, 10]]
Cond=[[False, True, False, True, True, True, True]]

for i in range(0,len(J[0])):
    if(Cond[0][i] == True):
        J[0][i] = 0 
print(J)
Answered By: NIVID K

Your code :

  1. J=[[0, 2, 0, 6, 7, 9, 10]]
  2. Cond=[[False, True, False, True, True, True, True]]
  3. for i in range(0,len(J[0])):
  4. if(Cond[0][i]==True):
    
  5.     J[0][i]==0
    
  6. print(J)

In line no.6 your statement : J[0][i]==0, here, the == operator is used for checking equality of the statement and returns a boolean value. So, your J[0][i] is only being compared with integer 0 and is not being assigned any value.
Assignment operator is =.
The correct statement for assignment would be : J[0][i]=0. After this, the J[0][i] would be assigned value as integer 0.
You only need to replace this line and you will get the required output.
So the corrected code would look like this :

  1. J=[[0, 2, 0, 6, 7, 9, 10]]
  2. Cond=[[False, True, False, True, True, True, True]]
  3. for i in range(0,len(J[0])):
  4. if(Cond[0][i]==True):
    
  5.     J[0][i]=0
    
  6. print(J)
Answered By: tan_000

You could use zip to pair up the lines and zip again to pair up the items of each line:

J=[[0, 2, 0, 6, 7, 9, 10]]
Cond=[[False, True, False, True, True, True, True]]

J = [ [(n,0)[c] for n,c in zip(rJ,rC)] for rJ,rC in zip(J,Cond) ]

print(J)

[[0, 0, 0, 0, 0, 0, 0]]
Answered By: Alain T.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.