How to replace each element in a list with its ordinal only the first time it appears using Python

1 Answer

0 votes
def replace_each_element_with_ordinal_first_time(lst):
    seen = set()
    result = []

    for i, x in enumerate(lst, start=1):
        if x not in seen:
            result.append(i)
            seen.add(x)
        else:
            result.append(x)

    return result

    
lst = ["a", "b", "c", "c", "b", "d", "e", "f", "g", "f"]

result = replace_each_element_with_ordinal_first_time(lst)

print(result)



'''
run:
 
[1, 2, 3, 'c', 'b', 6, 7, 8, 9, 'f']
 
'''
 

 



answered Feb 14 by avibootz
...