-2

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.

  • 2
    Possible duplicate of [compare two lists in python and return indices of matched values](https://stackoverflow.com/questions/10367020/compare-two-lists-in-python-and-return-indices-of-matched-values) – bharatk Aug 08 '19 at 07:55

4 Answers4

4

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]
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

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]
vaku
  • 697
  • 8
  • 17
0

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]
Taras
  • 77
  • 1
  • 2
  • 12
0
 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]]