I want to find the index of the value entered in n in the puzzle list below, but after 1, 2, 3, and 4 in the first list, the error keeps occurring. index = puzzle[i].index(n) This part seems strange, but I don't know how to fix it.
And if I can't find it, I want to return the return value None, and if I find it, I want to return the index value, what should I do?
puzzle= [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]]
def get_index(puzzle, n):
for i in range(len(puzzle)):
index = puzzle[i].index(n)
return index
get_index(puzzle, 3)
puzzle = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
def get_index(puzzle, n):
for idx1, i in enumerate(puzzle):
for idx2, j in enumerate(i):
if j == n:
return idx1, idx2
return None
get_index(puzzle, 10)
#(2, 1)
get_index(puzzle, 100)
#None
There are many ways, so I think the answer is to do what you think
For future reference... Upload
That's a pretty good code. It's not that hard. The index
found in the current state function isn't actually the answer, but it's the second index of the two-dimensional index you're looking for.
What is the first index? It's i
. So, if you find it, you can return (i, index)
.
The big problem right now is that I'm good at finding things in the first row like 3, but things like 7 are error-prone.
This is an error that occurs because 7 does not exist in the first line (i.e., puzzle[0]
). This is an error that can be avoided by checking the
if in puzzle[i]
condition in advance.
OK?
puzzle = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[3,14,15,16]]
def get_index(puzzle, n):
indice = []
for i, puz in enumerate(puzzle):
if n in puz:
indice.append(i)
return indice
get_index(puzzle, 3) # [0, 3]
© 2024 OneMinuteCode. All rights reserved.