'Count the number of occurrences different final word types succeeding the string
Suppose I have a list of lists like this
l = [['a', 'paragraph', 'is'],
['a', 'paragraph', 'can'],
['a', 'dog', 'barks']]
also suppose I have this smaller list a = ['a', 'paragraph'] I want to count the number of occurrences different final word types succeeding the string. Therefore, the answer in this case should be 2 since 'is' and 'can' succeed the string 'a paragraph'.
I was trying to do something like this
l.count(a)
but that did not work and gives me 0.
Ill try to spell this idea out more clearly, we basically have this substring 'a paragraph' and there are two occurrences that have 'a paragraph' namely 'is' and 'can', therefore since there is 2 unique cases the answer is 2.
Solution 1:[1]
You want to match each item in the list against the smaller list. We start by subsetting the larger list to match the size of the smaller list. If it doesn't match, we continue, ignoring that item. If it does match, we add the next item to a set. The set is important because it handles uniqueness.
items = [
['a', 'paragraph', 'is'],
['a', 'paragraph', 'can'],
['a', 'dog', 'barks']
]
check = ['a', 'paragraph']
check_len = len(check)
unique_words = set()
for item in items:
if item[:check_len] != check:
continue
unique_words.add(item[-1])
print(len(unique_words))
2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SNygard |
