python - Giving indices to list entries -
i have python list looking this:
a1 = ['a','a','a','foo','c','d','a','e','bar','bar','bar','e','d','d']
i want transform this...
a2 = [1,1,1,2,3,4,1,5,6,6,6,5,4,4]
...where entries in a1 taken in order , given incremental index in a2.
is there straight forward way in python?
one of ways of doing can be.
>>> a1 = ['a','a','a','foo','c','d','a','e','bar','bar','bar','e','d','d'] >>> ref = [] >>> in a1: ... if not in ref: ... ref.append(i) ... >>> [ref.index(i)+1 in a1] [1, 1, 1, 2, 3, 4, 1, 5, 6, 6, 6, 5, 4, 4]
logic
we remove duplicate values in original list (whilst preserving order). find index of individual items in list respect original list.
advantages
- simple concepts/ beginner level
- very straight forward.
disadvantages
- slow of order o(n2)
Comments
Post a Comment