Hammmad Iqbal
Hammmad Iqbal

Reputation: 23

Comparing one list with list of list and replace values

I have a list of list x which looks like this

[[3,6,7,8],
[2,4,5,7],
[4,5,8,10]]

and i have another list with 10 elements

y=[1,2,3,4,5,6,7,8,9,10]

i want to update x based on y so that it look like

[[0,0,1,0,0,1,1,1,0,0],
[0,1,0,1,1,0,1,0,0,0],
[0,0,0,1,1,0,0,1,0,1]]

my code looks like this

newlst3=[]
for x in range(10):
    newlst3.append(0)

for x in newlst:
    newlst3[x]=1

my code only does it for a single list but not for a list of lists

Upvotes: 1

Views: 56

Answers (3)

Piero
Piero

Reputation: 646

Double loop to iterate the elements of both lists and check for their presence.

ListX = [[3, 6, 7, 8], [2, 4, 5, 7], [4, 5, 8, 10]]
ListY = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
output = []

for element in ListX:

    list = []
    for index in ListY:

        if index in element:
            list.append(1)
        else:
            list.append(0)

    output.append(list)

OUTPUT

[[0, 0, 1, 0, 0, 1, 1, 1, 0, 0], [0, 1, 0, 1, 1, 0, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 1, 0, 1]]

Upvotes: 0

mozway
mozway

Reputation: 260410

If I understand correctly, you want to use the values in the first lists as indexes to set 1s in the final output. You can use a bit of numpy:

input:

import numpy as np
x = np.array([[3,6,7,8],
              [2,4,5,7],
              [4,5,8,10]])

processing:

out = np.zeros((x.shape[0], x.max()))
for i in range(x.shape[0]):
    out[i,x[i]-1]=1

output:

array([[0., 0., 1., 1., 0., 1., 1., 1., 1., 0.],
       [0., 1., 1., 1., 1., 1., 1., 1., 0., 0.],
       [0., 0., 0., 1., 1., 0., 0., 1., 0., 1.]])

Upvotes: 0

Jacob
Jacob

Reputation: 810

x = [[3, 6, 7, 8], [2, 4, 5, 7], [4, 5, 8, 10]]
y = list(range(1, 11))

output = []
for sublist in x:
    output.append([1 if i in sublist else 0 for i in y])

Upvotes: 1

Related Questions