I am using Python and I would like to check the location of a value in a list of lists against other indexes.
Like if I had 1 at (1, 1) I would want to be able to check if 1 were at the other indexes so I could make something happen based on which index it matched.
For example:
list_of_lists = [
[4, 5, 6],
[7, 1, 8],
[6, 2, 9]
]
if 1 in row for row in list_of_lists:
if index of 1 is (0, 0), (0, 1), or (0, 2)
print ("It is in the First row!")
if index of 1 is (1, 0), (1, 1), or (1, 2)
print ("It is in the second row!")
If this worked correctly it should print: “It is in the second row!” Because the index of 1 matches with one of the indices in the third if statement. They may not necessarily be rows in some instances where I would be using this. So If you could provide a way that would not use the rows in your answer. Just a way to look at indexes and compare them. Obviously this is not the correct syntax. But how would I do that in Python? How would I get the index of 1 and compare it to other indexes in a list of lists?
Thanks!
trying this in a python file:
outputs
[EDIT] As requested:
First of all, what does enumerate do?
source
As you can see, if you use enumerate, it will return both the index of the element AND the element. Therefore, while you’re iterating over the returned list you can access them and do what you desire. That’s what I’m doing here:
In that case, i stands for the row index, and r stands for row itself. ok?
In the next line you do the same thing, but now you’re enumerating the row itself, ok? And you’re getting, now, the indexes of the values j and the values c that are stored in each row.
Finally, when you return (i,j), you’re just returning a tuple that represents the values’s matrix index.