This is a pretty simple question about lists and for loop.
Assuming I have the following 2d-list:
[
['c', 'a', 't', 'c', 'a', 't']
['a', 'b', 'c', 'a', 't, 'l']
['c', 'a', 't', 'w', 'x', 'y']
]
And I want to iterate over the list using for loops, each time checking if the word 'cat' is in the list. If it is, I want to add it to the list every time it appears.
So my result should be ['cat', 'cat', 'cat, 'cat']
My function receives a word list and a given matrix (2d list containing lists of letters). My code is:
def search_for_words(word_list, matrix):
results = []
for word in word_list:
for line in matrix:
line_string = ''.join(line)
if word in line_string:
results.append(word)
return results
And it will returns me just 'cat' if cat is in thr word list.
I know I probably just need another if statement but I can figure it out.
Thanks in advance.
EDIT:
I gave a wrong example.
consider this:
matrix = [['a', 'p', 'p', 'l', 'e'],
['a', 'g', 'o', 'd', 'o'],
['n', 'n', 'e', 'r', 't'],
['g', 'a', 'T', 'A', 'C'],
['m', 'i', 'c', 's', 'r'],
['P', 'o', 'P', 'o', 'P']]
word_list = ['apple', 'god', 'dog', 'CAT', 'PoP', 'poeT]
my function returns :
['apple', 'god', 'PoP']
When I expect it to return 'PoP' twice because it appears twice at the bottom list.