How to find sequence of letters in a list of strings?

Viewed 83

Let's say I have the list:

lst1 = ['abc', 'abcde', 'abab', 'acd']

I want to create a dictionary to count the # of times 'ab' is in the list, so in this example, the dictionary would be {'ab': 4}. What do I do?

2 Answers

You could use a generator expression within sum

>>> lst1 = ['abc', 'abcde', 'abab', 'acd']
>>> {'ab': sum(i.count('ab') for i in lst1)}
{'ab': 4}

You can use the following:

>>> {'ab': ','.join(l).count('ab')}
{'ab': 4}
Related