python add an id for each element in list

  • A+
Category:Languages

I want to add an id for each element, if the elements occur multiple times, it should be added with the id when it occurs the first time, I have no idea for this problem, could anyone help me

input:

omg = ['a', 'b', 'c', 'a', 'b', 1] 

output:

omg_id = [0, 1, 2, 0, 1, 3] 

 


Little tricky solution to obtain ids in order of occurrence, using a defaultdict:

from collections import defaultdict  omg = ['a', 'b', 'c', 'a', 'b', 1] d = defaultdict(lambda: len(d))  # late binding allows d not to be defined yet omg_id = [d[x] for x in omg] # [0, 1, 2, 0, 1, 3] 

The default factory assigns the current number of known keys to every new key. Since key access not only returns but also assigns the value, the defaultdict "grows" during the comprehension.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: