Search code examples
pythonlistnesteddependenciesnaivebayes

count specific items in a nested list (x and y dependencies) inside python


Example I have these list

bersarang=[['Cerah','Tinggi','Lemah','Iya'],['Cerah','Tinggi','Kuat','Iya'],['Mendung','Tinggi','Lemah','Tidak'],['Hujan','Tinggi','Lemah','Iya'],['Hujan','Normal','Lemah','Iya'],['Hujan','Normal','Kuat','Tidak'],['Mendung','Normal','Kuat','Iya']]

then I want to count 'Cerah' and 'Iya' to an integer variable, the answer of these count should be 2. is it possible to get the count? I tried with count but its only count 1 item.

Failed Solution of mine:

bersarang.count('Cerah' and 'Iya')

Solution

  • You can use a for loop:

    Code Explantation:

    1. count = 0 setting count to 0

    2. for sub_l in l: iterating through the l

    3. if set(elems).issubset(sub_l): count += 1 add 1 to count if elems are in the sublist (sub_l)

    4. return count returning the count variable

    Code:

    def count_elems(elems, l):
        count = 0
    
        for sub_l in l:     
            if set(elems).issubset(sub_l):
                count += 1
    
        return count
    
    print(count_elems(['Iya', 'Cerah'], [['Cerah', 'Tinggi', 'Lemah', 'Iya'], ['Cerah', 'Tinggi', 'Kuat', 'Iya'], ['Mendung', 'Tinggi', 'Lemah', 'Tidak'], ['Hujan', 'Tinggi', 'Lemah', 'Iya'],
                 ['Hujan', 'Normal', 'Lemah', 'Iya'], ['Hujan', 'Normal', 'Kuat', 'Tidak'],
                 ['Mendung', 'Normal', 'Kuat', 'Iya']]))