ely66
ely66

Reputation: 185

calculate elements occurrence in a list

I have a list of elements:

l = ['a', 'b', 'b', 'a', 'c', 'd', 'd', 'c']

I want to produce a list with the elements occurrence, so for each element it counts how many times it appeared until this point:

Such that I will get:

elements_occurence: [1, 1, 2, 2, 1, 1, 2, 2]

I tried:

occurrences = {}
for i in l:
    if i in occurrences:
        occurrences[i] += 1
    else:
        occurrences[i] = 1

But it gives me this result instead:

{'a': 2, 'b': 2, 'c': 2, 'd': 2}

Upvotes: 0

Views: 55

Answers (1)

Tomerikoo
Tomerikoo

Reputation: 19395

You are currently just checking the end result of the dict. But if you "save" the intermediate values while iterating, you will get your result:

occurrences = {}
elements_occurence = []
for i in l:
    if i in occurrences:
        occurrences[i] += 1
    else:
        occurrences[i] = 1
    elements_occurence.append(occurrences[i])
print(elements_occurence)
print(occurrences)

Gives:

[1, 1, 2, 2, 1, 1, 2, 2]
{'a': 2, 'b': 2, 'c': 2, 'd': 2}

A few ways to improve your counting (in ascending order of being "pythonic"):

  1. Use setdefault:

    for i in l:
        occurrences[i] = occurrences.setdefault(i, 0) + 1
    
  2. Use get:

    for i in l:
        occurrences[i] = occurrences.get(i, 0) + 1
    
  3. Use defaultdict:

    from collections import defaultdict
    
    occurrences = defaultdict(int)
    for i in l:
        occurrences[i] += 1
    

Upvotes: 3

Related Questions