Yair
Yair

Reputation: 909

Python - count the occurrences of a list of items in a list?

Trying to count how many times a value from a list appears in another list. In the case of:

my_list = [4,4,4,4,4,4,5,8]
count_items = [4,5,8]

this works fine:

from collections import Counter
print (Counter(my_list))
>> Counter({4: 6, 5: 1, 8: 1})

However, if my_list does not have any entries for '4', for example

my_list = [5,8] 
count_items = [4,5,8]
print (Counter(my_list))
>> Counter({5: 1, 8: 1})

While I am looking for this output:

>> Counter({4: 0, 5: 1, , 8: 1})

Upvotes: 0

Views: 82

Answers (3)

wim
wim

Reputation: 362488

A counter is a dict and implements the update method, which preserves zeros:

>>> counter = Counter(my_list)
>>> counter
Counter({5: 1, 8: 1})
>>> counter.update(dict.fromkeys(count_items, 0))
>>> counter
Counter({5: 1, 8: 1, 4: 0})

Upvotes: 0

Diogo Pinto
Diogo Pinto

Reputation: 154

Counter has no way to know that you would expect 4s to be counted, so by default only accounts for elements it finds in the list. An alternative approach would be:

my_list = [5,8]
count_items = [4,5,8]
counter = {i: sum(map(lambda x: 1 if x == i else 0, my_list)) for i in count_items}
print (counter)
>> {4: 0, 5: 1, 8: 1}

Upvotes: 0

Encrypted
Encrypted

Reputation: 188

What do you need the value for?

Because the counter you have here actually returns 0 when asked for the key 4:

my_list = [5,8] 
count_items = [4,5,8]
counter = Counter(my_list)
print(counter)
>> Counter({5: 1, 8: 1})
print(counter[4])
>> 0

Upvotes: 1

Related Questions