I want to take two lists to convert the values of element if element match.
l1 = ['p', 'n', 'c', 'k', 'e']
l2 = [['n', 'p', 'e'], ['n', 'e']]
would return [[1, 1, 0, 0, 1],[1, 0, 0, 0, 1]] for instance.
I want to take two lists to convert the values of element if element match.
l1 = ['p', 'n', 'c', 'k', 'e']
l2 = [['n', 'p', 'e'], ['n', 'e']]
would return [[1, 1, 0, 0, 1],[1, 0, 0, 0, 1]] for instance.
Using a list comprehension .
Ex:
l1 = ['p', 'n', 'c', 'k', 'e']
l2 = ['n', 'p', 'e']
print([int(i in l2) for i in l1]) #--> [1, 1, 0, 0, 1]
Try using in
keyword and inline loop
l1 = ['p', 'n', 'c', 'k', 'e']
l2 = ['n', 'p', 'e']
newList = [1 if x in l2 else 0 for x in l1]
print(newList) # [1, 1, 0, 0, 1]
Maybe if you want to use a simple loop:
l1 = ['p', 'n', 'c', 'k', 'e']
l2 = ['n', 'p', 'e']
l3=[]
for i in l1:
if i in l2:
l3.append(1)
else:
l3.append(0)
print(l3) #[1, 1, 0, 0, 1]
l1 = ['p', 'n', 'c', 'k', 'e']
l2 = [['n', 'p'], ['c', 'k', 'e']]
result = []
for l in l2:
re = []
for j in l1:
if j in l:
re.append(1)
else:
re.append(0)
result.append(re)
print(result) # [[1, 1, 0, 0, 0], [0, 0, 1, 1, 1]]