-2
testlist = [[1, 2, 3, 0, 0], [0, 0, 3, 2, 1], [1, 0, 0, 3, 2], [2,3,1,0,0], [3,0,1,2,0], [2,0,1,3,0]]

I would like to check if the number 1 is in the third column of all the nested lists, if it is than it should replace the 1 with a 0 and the 2 in that list with a 1.

Thanks in advance

JoeJunior
  • 1
  • 3

2 Answers2

1

You can try this:

testlist = [[1, 2, 3, 0, 0], [0, 0, 3, 2, 1], [1, 0, 0, 3, 2], [2,3,1,0,0],[3,0,1,2,0], [2,0,1,3,0]]
for ind,ele in enumerate(testlist):
    if ele[2] == 1:
        testlist[ind] = [i-1 if i in [1,2] else i for i in ele]

This should give you the output as follows

Input: testlist = [[1, 2, 3, 0, 0],
                   [0, 0, 3, 2, 1],
                   [1, 0, 0, 3, 2],
                   [2, 3, 1, 0, 0],
                   [3, 0, 1, 2, 0],
                   [2, 0, 1, 3, 0]]
Output: testlist -> [[1, 2, 3, 0, 0],
                     [0, 0, 3, 2, 1],
                     [1, 0, 0, 3, 2],
                     [1, 3, 0, 0, 0],
                     [3, 0, 0, 1, 0],
                     [1, 0, 0, 3, 0]]
Parth Verma
  • 710
  • 1
  • 7
  • 15
-1

For this, consider the testlist to be a matrix. You can solve this by using two for loops to loop each row and column.

testlist = [[1, 2, 3, 0, 0], [0, 0, 3, 2, 1], [1, 0, 0, 3, 2], [2,3,1,0,0], [3,0,1,2,0], [2,0,1,3,0]]

#traversing each row
for i, row in enumerate(testlist):
#traversing each column
   for j, c in enumerate(row):
   #in each column in the row check for '1', if found replace by '0'
      if j == 2 and c== 1:
         row[j] = 0
         #in the same row check for '2', if found replace my 1
         if 2 in row:
            ind = row.index(2)
            row[ind] = 1
print (testlist)