Timofey Goritsky
Timofey Goritsky

Reputation: 89

Create a comparison list from two lists

I am doing a list comparison and I feel like I`ve run out of possible approaches. This is the situation: I have two lists, for example:

[00, 11, 22, 33, 44, 55]

And:

[22, 55]

What I need is to construct a comparison list from those two looking like this:

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

Where 1 is put if an element is in a list and 0 is put if there is no such element. A comparison list should be ordered. I can`t find a clue for the correct approach here, so I am asking for an assistance.

Upvotes: 0

Views: 93

Answers (3)

Ajax1234
Ajax1234

Reputation: 71461

You can use map:

d = [00, 11, 22, 33, 44, 55]
s = [22, 55] 
new_d = list(map(lambda x:int(x in s), d))

Output:

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

Upvotes: -1

Ma0
Ma0

Reputation: 15204

Another list-comprehension that is a bit more compact:

l1 = [00, 11, 22, 33, 44, 55]
l2 = [22, 55]

res = [int(i in l2) for i in l1]

which also returns the desired:

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

Note:

int(True) == 1 and int(False) == 0

Upvotes: 3

Rakesh
Rakesh

Reputation: 82785

Using a list comprehension.

Demo:

l1 = [00, 11, 22, 33, 44, 55]
l2 = [22, 55]
print([1 if i in l2 else 0 for i in l1])

Output:

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

Upvotes: 5

Related Questions