Home > Back-end >  How to update the values of 2d list from 1d list?
How to update the values of 2d list from 1d list?

Time:08-18

Hello how can I update my 2D array list using my 1D array list

Here my code so far:

x2D=[[0,1],[1,1],[0,0]]
x1D = [1,0,0,1,1,0]

for x in range(2): #index of 2D
    for y in range(6): #index 1D
        if x1D in x2D[x]:
            x2D[x][0:y] == x1D[y]

print(x2D)

I want to change the all the value of 1 into 0 in 2D if 1D has 0 in that index: I want the output to be like this: x2D=[[0,0],[0,1],[1,0]]

CodePudding user response:

Alternative, using a couple of for loops that does the following:

I want to change the all the value of 1 into 0 in 2D if 1D has 0 in that index

>>> x2D = [[0, 1], [1, 1], [0, 0]]
>>> x1D = [1, 0, 0, 1, 1, 0]
>>> m, n = len(x2D), len(x2D[0])
>>> for i in range(m):
...     for j in range(n):
...         if x2D[i][j] == 1 and x1D[i * n   j] == 0:
...             x2D[i][j] = 0
...
>>> x2D
[[0, 0], [0, 1], [0, 0]]

CodePudding user response:

The easiest might be to create a flat list with the new values and then chunk it again into a list of lists:

>>> from itertools import chain
>>> x2D = [[0, 1], [1, 1], [0, 0]]
>>> x1D = [1, 0, 0, 1, 1, 0]
>>> r = [a and b for a, b in zip(chain.from_iterable(x2D), x1D)]
[0, 0, 0, 1, 0, 0]
>>> [r[i:i   2] for i in range(0, len(r), 2)]
[[0, 0], [0, 1], [0, 0]]

(I'm assuming you want an and condition for the values, as your given example is inconsistent.)

  • Related