hans glick
hans glick

Reputation: 2611

Counter occurrences within the same item in python

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.

Upvotes: 3

Views: 59

Answers (4)

Totoro
Totoro

Reputation: 887

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])))

Upvotes: 1

G_M
G_M

Reputation: 3372

>>> 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]

Upvotes: 1

Amaro Vita
Amaro Vita

Reputation: 436

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

Upvotes: 2

user3483203
user3483203

Reputation: 51155

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]

Upvotes: 3

Related Questions