3

Sorry, I'm pretty sure that somebody else may have asked this question already but I did not find it. I'd like to keep track the number of times I've seen this specific item like

Input :

[88,88,27,0,88]

Desired Output :

[1,2,1,1,3]

I'm looking for something especially good in terms of performance. I'm ok with Numpy or Pandas solutions.

hans glick
  • 2,431
  • 4
  • 25
  • 40

4 Answers4

3

Here is a simple way using a list comprehension:

x = [8,1,2,3,1,3,3,1,2,99]
y = [x[:i].count(el) + 1 for i, el in enumerate(x)]
print(y)

Output:

[1, 1, 1, 1, 2, 2, 3, 3, 2, 1]
user3483203
  • 50,081
  • 9
  • 65
  • 94
2
lst = [8,1,2,3,1,3,3,1,2,99]

cnt = {}
res = []

for x in lst:
    cnt[x] = cnt.get(x,0)+1
    res += [cnt[x]]

print(res)

Output

Amaro Vita
  • 437
  • 3
  • 9
1
>>> from collections import defaultdict
... 
... 
... def solution(lst):
...     result = []
...     seen = defaultdict(int)
...     for num in lst:
...         seen[num] += 1
...         result.append(seen[num])
...     return result
... 
>>> solution([88, 88, 27, 0, 88])
[1, 2, 1, 1, 3]
>>> solution([8, 1, 2, 3, 1, 3, 3, 1, 2, 99])
[1, 1, 1, 1, 2, 2, 3, 3, 2, 1]

Without imports:

>>> def solution(lst):
...     result = []
...     seen = {}
...     for num in lst:
...         try:
...             seen[num] += 1
...         except KeyError:
...             seen[num] = 1
...         result.append(seen[num])
...     return result
... 
>>> solution([88, 88, 27, 0, 88])
[1, 2, 1, 1, 3]
>>> solution([8, 1, 2, 3, 1, 3, 3, 1, 2, 99])
[1, 1, 1, 1, 2, 2, 3, 3, 2, 1]
G_M
  • 3,342
  • 1
  • 9
  • 23
1

one with generators:

def return_count(l):
    cnt = {}
    for x in l:
        cnt[x] = cnt.get(x, 0) + 1
        yield cnt[x]

print(list(return_count([8, 1, 2, 3, 1, 3, 3, 1, 2, 99])))
Totoro
  • 867
  • 9
  • 10