-1

For example my list is

lst=['hello','world','this','is','hello','world','world','hello']
subString=['hello','world']

The result I'm looking for is in this case is 2 since the list ['hello','world'] occurs twice with that same order.

I tried doing

list(filter(lambda x : x in substring,lst))

but that returns all of hello and world

qBoss
  • 63
  • 5
  • See https://stackoverflow.com/a/6822773/6779307 – Patrick Haugh Sep 29 '18 at 23:02
  • What if the array looks like this: `['hello', 'world', 'hello world', 'hello', 'world hello']`? The currently accepted answer falls apart if your goal is to ensure that two consecutive list items create the string `'hello world'`. It may work for the specific example you've provided but it is not a great general-purpose answer. The one I have provided accounts for such a scenario. – Matt Sep 30 '18 at 00:39

4 Answers4

0

You can join the elements into a list of lists and then filter by those that match your substring array.


joinedWords = [lst[n:n + len(subString)] for n in range(0, len(lst), len(subString))]
    # => [['hello', 'world'], ['this', 'is'], ['hello', 'world'], ['world', 'hello']]
filtered = list(filter(lambda x: x == subString, joinedWords))

print(len(filtered))  # 2
Matt
  • 2,953
  • 3
  • 27
  • 46
0

You could use " ".join() on both lists to create a string and then use str.count() to count the number of occurrences of subString in lst

lst=['hello','world','this','is','hello','world','world','hello']
subString=['hello','world']

l = " ".join(lst)
s = " ".join(subString)

count = l.count(s)
print("Joined list:", l)
print("Joined substring:", s)
print("occurrences:", count)

outputs:

Joined list: hello world this is hello world world hello
Joined substring: hello world
occurrences: 2
Jebby
  • 1,845
  • 1
  • 12
  • 25
0

Since all elements are string in this case, I'd create a string from each list, then count the occurrences of the second string in the first string:

lst=['hello','world','this','is','hello','world','world','hello']
subString = ['hello','world']

s = ' '.join(lst)
subs = ' '.join(subString)

print(s.count(subs))
dvnguyen
  • 2,954
  • 17
  • 24
  • This will give you false positives if you have an array like `['hel', 'low', 'orld']`. You need to join with a space (in which case your answer would be exactly the same as the accepted answer). – Matt Sep 30 '18 at 00:35
0

Using the window generator from this answer and a Counter, this can be expressed as:

from collections import Counter

lst=['hello','world','this','is','hello','world','world','hello']
subString=('hello','world')

counts = Counter(window(lst, len(subString)))

print(counts[subString])
# 2

If you want to skip the Counter, you could do

print(sum(x == subString for x in window(lst, len(subString))))
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96