I want this code to append 1 for the first occurence of an item in list p that occurs in list s, and append 0 for the other occurence and other items in s.
That’s my current code below and it is appending 1 for all occurences, I want it to append 1 for the first occurence alone. Please, help
s = [20, 39, 0, 87, 13, 0, 23, 56, 12, 13]
p = [0, 13]
bin = []
for i in s:
if i in p:
bin.append(1)
else:
bin.append(0)
print(bin)
# current result [0, 0, 1, 0, 1, 1, 0, 0, 0, 1]
# excepted result [0, 0, 1, 0, 1, 0, 0, 0, 0, 0]
>Solution :
The simplest solution is to remove the item from list p if found:
s = [20, 39, 0, 87, 13, 0, 23, 56, 12, 13]
p = [0, 13]
out = []
for i in s:
if i in p:
out.append(1)
p.remove(i)
else:
out.append(0)
print(out)
Prints:
[0, 0, 1, 0, 1, 0, 0, 0, 0, 0]