-6

I understand the counter function counts the frequency of every element in a list. But I would like it to include the frequency from given elements even the element doesn't appear in the list.

for example:

A list of expected elements are given as:

expected_element = [1,2,3,4,5,6,7]

for the datasets a,b:

a = [1,1,1,1,6,6,6,3,3,4,5,5]
b = [2,2,7,1,7,5,3,5,5]

and what I want is to count frequency of expected_element in a and b:

for a:

keys() =   [1,2,3,4,5,6,7]
values() = [4,0,2,1,2,3,0]

for b:

keys() =   [1,2,3,4,5,6,7]
values() = [1,2,1,0,3,0,2]    
Ignacio Vergara Kausel
  • 5,521
  • 4
  • 31
  • 41
FF0605
  • 441
  • 7
  • 17

2 Answers2

0

You can use dict

expected_element = [1,2,3,4,5,6,7]
a = [1,1,1,1,6,6,6,3,3,4,5,5]
b = [2,2,7,1,7,5,3,5,5]

a_occurance = dict()
b_occurance = dict()
for i in expected_element:
    a_occurance[i]=0
    b_occurance[i]=0
for i in a:
    a_occurance[i]+=1
for i in b:
    b_occurance[i]+=1

print a_occurance.keys()
# [1, 2, 3, 4, 5, 6, 7]
print a_occurance.values()
# [4, 0, 2, 1, 2, 3, 0]
print b_occurance.keys()
# [1, 2, 3, 4, 5, 6, 7]
print b_occurance.values()
# [1, 2, 1, 0, 3, 0, 2]
Mitiku
  • 5,337
  • 3
  • 18
  • 35
0

You can create a dictionary with the unique keys in set(a), paired with null values, then update it with Counter(b):

from collections import Counter

a = [1,1,1,1,6,6,6,3,3,4,5,5]
b = [2,2,7,1,7,5,3,5,5]

frequencies = {key: 0 for key in set(a)}
frequencies.update(Counter(b))
print(frequencies)

output:

{1: 1, 3: 1, 4: 0, 5: 3, 6: 0, 2: 2, 7: 2}
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80