Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find the number of occurrence of a string in a list of list

I have a list in the following format.

my_list=[['xyz','abc','Qwerty 1','Qwerty 2'],[],['1','2','Qwerty 1','Qwerty 2',1,4,'Qwerty 3',3],['1','QQQ','Quit','Qual','Qwerty 1']]

I’m trying to find the number of times the string ‘Qwerty’ appears in the list of list and return a list of list with the number of occurrence.

Desired out put would like like this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

count_list=[[2],[],[3],[1]]

My MEW:

my_list=[['xyz','abc','Qwerty 1','Qwerty 2'],[],['1','2','Qwerty 1','Qwerty 2',1,4,'Qwerty 3',3],['1','QQQ','Quit','Qual','Qwerty 1']]
dummy_list=[]

       
for list in my_list:
    q_count=list.count('Qwerty')
    dummy_list.append(q_count)

count_list=[[el]for el in dummy_list]

print(count_list)

The issue im having is it works well for single word/letter but the moment i add a number at the end, it returns 0. Is there an approximate function?

>Solution :

my_list = [
    ['xyz', 'abc', 'Qwerty 1', 'Qwerty 2'],
    [],
    ['1', '2', 'Qwerty 1', 'Qwerty 2', 1, 4, 'Qwerty 3', 3],
    ['1', 'QQQ', 'Quit', 'Qual', 'Qwerty 1']
]
count_list = []
       
for list in my_list:
    q_count = 0
    for str_val in list:
        if 'Qwerty' in str(str_val):
            q_count += 1
    count_list.append([q_count])
print(count_list)

prints out:

[[2], [0], [3], [1]]

if you want to print out an empty list instead of a list containing 0 when the string is not found, you can use:

my_list = [
    ['xyz', 'abc', 'Qwerty 1', 'Qwerty 2'],
    [],
    ['1', '2', 'Qwerty 1', 'Qwerty 2', 1, 4, 'Qwerty 3', 3],
    ['1', 'QQQ', 'Quit', 'Qual', 'Qwerty 1']
]
count_list=[]
       
for list in my_list:
    q_count = 0
    for str_val in list:
        if 'Qwerty' in str(str_val):
            q_count += 1
    count_list.append([q_count] if q_count > 0 else [])
print(count_list)

to print out

[[2], [], [3], [1]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading