Home > database >  How to find sequence of letters in a list of strings?
How to find sequence of letters in a list of strings?

Time:11-19

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?

CodePudding user response:

You could use a generator expression within sum

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

CodePudding user response:

You can use the following:

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