return a binary list elements between two lists based on a condition

Viewed 174

I have the following two lists:

A = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
B = ['b', 'd', 'f', 'g']

Of which I want to check if elements of B are in Athen 0 else 1. The expected output should be like this:

{'C': [0, 1, 0, 1, 0, 1, 1]}

I tried the following but didn't get what I am expecting.

{'C': [int(i == j) for j in A] for i in B}
3 Answers

as @Boris mentioned using set(B) would be much faster if its a long list.

{'C': [int(value in set(B)) for value in A] }

output :

{'C': [0, 1, 0, 1, 0, 1, 1]}

As per your expected output (If A element is in B):

[1 if x in B else 0 for x in A]
A = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
B = ['b', 'd', 'f', 'g']

C = [1 if a in B else 0 for a in A]

This is a one liner achieving what you are looking for. Nice and simple.

Related