This problem seems really stupid bu I can’t get my head around it.
I have the following list:
a = [2, 1, 3, 1, 1, 2, 3, 2, 3]
I have to produce a second list which have the same size as the previous one but the values that appear should be the amount of times that a value showed up in the array until that point. For example:
b = [1, 1, 1, 2, 3, 2, 2, 3, 3]
So b[0] = 1 because it’s the first time the item ‘2’ appear on the ‘a’ list. b[5] = 2 and b[7] = 3 because it’s the second and third time that the item ‘2’ appear on the list ‘a’.
Advertisement
Answer
Here a solution:
from collections import defaultdict a = [2, 1, 3, 1, 1, 2, 3, 2, 3] b = [] d = defaultdict(int) for x in a: d[x] +=1 b.append(d[x]) print(b)
Output:
[1, 1, 1, 2, 3, 2, 2, 3, 3]