Skip to content Skip to sidebar Skip to footer

Count Occurrences Of Search Strings In A List

I have the following list: data_items = ['abc','123data','dataxyz','456','344','666','777','888','888', 'abc', 'xyz'] And I have a list of search items: search = ['abc','123','xyz

Solution 1:

You could use re.search and a collections.Counter, eg:

import re
from collections import Counter

data_items = ['abc','123data','dataxyz','456','344','666','777','888','888', 'abc', 'xyz']
search = ['abc','123','xyz','456']

to_search = re.compile('|'.join(sorted(search, key=len, reverse=True)))
matches = (to_search.search(el) for el in data_items)
counts = Counter(match.group() formatchin matches ifmatch)
# Counter({'abc': 2, 'xyz': 2, '123': 1, '456': 1})

Solution 2:

Looks like you need a partial match too. Code below is intuitive but may not be efficient. And also assumes you're ok with dict result.

>>> data_items = ['abc','123data','dataxyz','456','344','666','777','888','888', 'abc', 'xyz']
>>> search = ['abc','123','xyz','456']
>>> result = {k:0 for k in search}
>>> for item in data_items:
        for search_item in search:
            if search_item in item:
                result[search_item]+=1
>>> result
{'123': 1, 'abc': 2, 'xyz': 2, '456': 1}

Solution 3:

counts={}
for s in search:
    lower_s=s.lower()  
    counts[lower_s]=str(data_items.count(lower_s))

That's if you are ok with using a dictionary (since you said structure, it's a better choice).

Post a Comment for "Count Occurrences Of Search Strings In A List"