Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

weighted counting in python

Tags:

python

count

I want to count the instances of X in a list, similar to

How can I count the occurrences of a list item in Python?

but taking into account a weight for each instance.

For example,

L = [(a,4), (a,1), (b,1), (b,1)]

the function weighted_count() should return something like

[(a,5), (b,2)]

Edited to add: my a, b will be integers.

like image 383
Admiral Tso Avatar asked Dec 27 '25 16:12

Admiral Tso


2 Answers

you can still use counter:

from collections import Counter
c = Counter()
for k,v in L:
    c.update({k:v})
print c
like image 115
Fabricator Avatar answered Dec 30 '25 07:12

Fabricator


The following will give you a dictionary of all the letters in the array and their corresponding counts

counts = {}
for value in L:
    if value[0] in counts:
        counts[value[0]] += value[1]
    else:
        counts[value[0]] = value[1]

Alternatively, if you're looking for a very specific value. You can filter the list for that value, then map the list to the weights and find the sum of them.

def countOf(x,L):
    filteredL = list(filter(lambda value: value[0] == x,L))
    return sum(list(map(lambda value: value[1], filteredL)))
like image 45
mattsap Avatar answered Dec 30 '25 06:12

mattsap



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!