You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从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 board is a 2D list (a list containing other lists). When you call board.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 your board is an integer (like 8, 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 in board to 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 returns None.

内容的提问来源于stack exchange,提问作者martin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 14:32:49