【问题标题】:Error in code, for program that asks input of index for 2d array and outputs the value at that index代码错误,对于要求输入二维数组的索引并输出该索引处的值的程序
【发布时间】:2025-12-19 09:25:12
【问题描述】:

我有一项任务需要执行以下操作:

编写一个程序,允许用户输入整数值并查询大小为 9x9 的二维数组。然后,您的程序应该向用户询问一对坐标 (x, y),以空格分隔,并返回给定坐标指定位置处的值。例如,0 3 应该返回值 7(第一行第四列的​​值——记住数组索引从零开始)。假设每个整数都是从 1 到 9 的单个数字。输入 -1 作为任一坐标以结束程序。

我不断收到此错误:

以 10 为基数的 int() 的无效文字:''

这是代码:

print("Enter an array:")
array_9x9 = [input() for i in range(9)]    

while True:
    # Read a line of coordinates, split into two elements, convert to integers
    x, y = map(int, input("Enter coordinates: ").split(' ', 2))
               
    # Stop if sentinel in either coordinate
    if -1 in (x, y):
        print("DONE")
        break
    # print the element at the specified coordinates
    print('Value = ' [array_9x9[x][y]])

这是输出:

Sample I/O:
Enter an array:
359716482
867345912
413928675
398574126
546281739
172639548
984163257
621857394
735492861
Enter coordinates:
0 3
Value = 7
Enter coordinates:
5 5
Value = 9
Enter coordinates:
8 8
Value = 1
Enter coordinates:
-1 -1
DONE

【问题讨论】:

  • map(int, ...) 行同时执行的操作超出了您目前所能理解的范围。将它分成几行,每行只做一件事,以了解错误发生的位置。这也允许您打印中间值以检查它们是否符合您的预期。
  • 在示例输入和输出中的什么时候发生错误?看起来一切正常。

标签: python arrays sentinel


【解决方案1】:

您没有处理用户输入无效值时发生的错误。当提示用户是否只是不输入任何内容并点击时,您会看到您描述的错误。同样,如果用户输入非数字或意外值,您将收到类似的错误。

while True:
    try:
        x, y = map(int, input("Enter coordinates: ").split(' ', 2))
    except ValueError:
        continue
               
    if -1 in (x, y):
        print("DONE")
        break

    print('Value = ', array_9x9[x][y])  # fixed this line

如果用户输入无效索引的有效数字(例如 12 或 -2),您还可以考虑额外的错误处理。

【讨论】: