-1

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]]

Zanjel
  • 13
  • 2
  • What about the second to last index? In 2D this changes to a 1, is that expected? – ChrisOram Aug 17 '22 at 09:43
  • The first value and the second-to-last are the same case, `0` and `1`, yet the outcome is somehow different…?! You seem to be unclear about your own logic. Is it possible to simply say you want an "`and`" case? If both values are `1`, keep `1`, else `0`. – deceze Aug 17 '22 at 09:46

2 Answers2

0

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.)

deceze
  • 510,633
  • 85
  • 743
  • 889
0

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]]
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40