如何从Python多维列表中获取指定元素的索引?
Fixing the ValueError When Finding an Index in a 2D List
Hey there! Let's break down why you're hitting that ValueError: '8' is not in the list error, and how to get the correct index for your target element.
Why the Error Happens
You've got two key issues here:
- Your
boardis a 2D list (a list containing other lists). When you callboard.index("8"), Python looks for the string"8"directly in the top-level list—meaning it checks if any sublist (like[0,1,2,3]) equals"8", which it never will. - Type mismatch: You're searching for the string
"8", but every element in yourboardis an integer (like8, not"8"). Even if this were a 1D list, Python wouldn't find a match because the types don't align.
How to Get the Correct Index
To find an element in a 2D list, you need to iterate through each row, then check each element within that row. Here's a straightforward helper function to do this:
board = [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]] def find_2d_index(arr, target): # Iterate through each row with its index for row_num, row in enumerate(arr): try: # Look for the target in the current row col_num = row.index(target) return (row_num, col_num) # Return (row, column) if found except ValueError: # If target isn't in this row, move to the next one continue # Return None if the target doesn't exist in the list return None # Search for the integer 8 (matches the type in your board!) result = find_2d_index(board, 8) print(result) # Output: (2, 0)
Quick Notes
- If you really need to search for the string
"8"instead of the integer, you'd first need to convert all elements inboardto strings, or adjust the function to check for string versions of elements. But matching the integer type is the simpler, more logical fix here. - The function returns a tuple
(row_index, column_index)—this is the standard way to represent positions in a 2D list. If the target isn't present anywhere, it returnsNone.
内容的提问来源于stack exchange,提问作者martin
相关产品推荐
相关产品推荐

