Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading