Home > Software design >  calculate elements occurrence in a list
calculate elements occurrence in a list

Time:03-20

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}

CodePudding user response:

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
    

CodePudding user response:

You could use a list comprehension as follows:

lst = ['a', 'b', 'b', 'a', 'c', 'd', 'd', 'c']
output = [lst[:e].count(v) for e, v in enumerate(lst, 1)]
print(output)

Output:

[1, 1, 2, 2, 1, 1, 2, 2]

CodePudding user response:

not getting your question exactly what you are expecting.

can you please elaborate your question with expected answer ?

  • Related