Reputation: 89
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
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
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
andint(False) == 0
Upvotes: 3
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