Check if a value is the first occurence of a list and mark as 1 in Python

Viewed 136

I have a list and I want to mark the first occurrence of each element as 1, and other occurrences as 0s. How should I do that?

Inital Input:

my_lst = ['a', 'b', 'c', 'c', 'a', 'd']

Expected outputs:

[1,1,1,0,0,1]
3 Answers

You can use itertools.count and collections.defaultdict for the task:

from itertools import count
from collections import defaultdict

my_lst = ['a', 'b', 'c', 'c', 'a', 'd']

d = defaultdict(count)
out = [int(next(d[v])==0) for v in my_lst]
print(out)

Prints:

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

If you want a barebones python solution, this monstrosity would work:

[*map(int, map(lambda x, y: x == my_lst.index(y), *zip(*enumerate(my_lst))))]
Out[30]: [1, 1, 1, 0, 0, 1]

For all items in my_lst, it returns 1 if its index is the index of the first occurrence.

you will need to keep track of which items you saw already so here's an example code:

seen_chars = set()
output = []

for c in my_lst:
    if c not in seen_chars:
        seen_chars.add(c)
        output.append(1)
    else:
        output.append(0)

Hope that helped

Related