How do you compare a matrix row (ie list of lists) with a given string?
index = 99999
for i in range(len(text)):
if (matrix[i][0:len(text)] == text):
index = i
I want “index” to be the number of row for which “row == text”, but the above code outputs 99999.
I know for sure that exactly one of the rows contains the string.
For example, the matrix is
['a', 'i', 'n', 'e', 'm']
['e', 'm', 'a', 'i', 'n']
['i', 'n', 'e', 'm', 'a']
['m', 'a', 'i', 'n', 'e']
['n', 'e', 'm', 'a', 'i']
and I want to know which row is “maine” (number 3 in this case).
Thanks!
Try
list(text)turns the string into a list of characters.list.indexsearches for the item you specify (using==as the equality comparison) and returns its index if found, or raisesIndexErrorif not found.I’d also not recommend using
99999as the ‘not found’ value; it’s rather safer to use a value like -1 or (better yet) just leave the exception alone unless you intend to handle it.If you know the string must be in the matrix, then
index = matrix.index(list(text))is all you need.