Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count sublists that has a specific term in python

I'm a newbie I want to write a function that outputs the count of sublists that contain a particular element. But my function just outputs the total count of that particular term in all the sublists.

My function:

def count(myList):
    tmp = []
    d = {}
    for item in myList: tmp += item
    for key in tmp: d[key] = d.get(key, 0) + 1
    return d

My output:

>>res = count_doc_frequencies([['a', 'b', 'a'], ['a', 'b', 'c'], ['a']])
>>res['a']
4
>>res['b']
2

Desired output:

>>res = count_doc_frequencies([['a', 'b', 'a'], ['a', 'b', 'c'], ['a']])
>>res['a']
3

As 'a' is present in 3 sublists..

can anyone help me modify my function to achieve the desired output ??

like image 435
Wolf Avatar asked Jul 17 '26 19:07

Wolf


2 Answers

lst = [['a', 'b', 'a'], ['a', 'b', 'c'], ['a']]

def count(lst):
    # declare dictionary that we are going to return
    foo = {}
    # iterate sublist
    for sublist in lst:
        # make sublist into unique element list
        sublist = list(set(sublist))
        for element in sublist:
            # if element found in foo dic, increment
            if element in foo:
                foo[element] += 1
            # else, init with 1
            else:
                foo[element] = 1
    return foo

res = count(lst)
print res
like image 180
taesu Avatar answered Jul 20 '26 07:07

taesu


You should change this statement

tmp += item

to

tmp += set(item)

This will eliminate the duplication count of elements in your sublists.

like image 25
zhangxaochen Avatar answered Jul 20 '26 08:07

zhangxaochen



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!