list indices必须是整数或切片,而不是来自2D数组python的列表

时间:2017-12-05 22:46:38

标签: python list for-loop multidimensional-array error-handling

我从python中得到了这个错误:

TypeError: list indices must be integers or slices, not list

使用此代码时:

a1, a2, a3, a4, a5, a6, a7, a8, b1, b2, b3, b4, b5, b6, b7, b8 = "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "g1", "g2", "g3", "g4", "g5", "g6", "g7", "g8", "h1", "h2", "h3", "h4", "h5", "h6", "h7", "h8" 
bord = [[a1, a2, a3, a4, a5, a6, a7, a8], [b1, b2, b3, b4, b5, b6, b7, b8], [c1, c2, c3, c4, c5, c6, c7, c8], [d1, d2, d3, d4, d5, d6, d7, d8], [e1, e2, e3, e4, e5, e6, e7, e8], [f1, f2, f3, f4, f5, f6, f7, f8], [g1, g2, g3, g4, g5, g6, g7, g8], [h1, h2, h3, h4, h5, h6, h7, h8]]


for y in bord:
    for x in bord[y]:
        print(bord[y][x])

所以我创建了一个8乘8的棋盘(2D列表),其中有象棋的名字。 我想为每个单独的方块执行一段代码。

第一个for循环将一次选择1行(因此y为y轴) 那么第二个for循环将一次选择1列(因此x为x轴)

对于测试,我刚刚打印了2D列表的位置:

print(bord[y][x])

1 个答案:

答案 0 :(得分:0)

for y in bord:
    for x in bord[y]:
        print(bord[y][x])

这是错误的,正确的做法是:

for y in bord:
    for x in y:
        print(x)

这是因为for x in arr遍历数组并将元素保存在变量x中,如果您想要执行bord[y][x]的样式,请执行以下操作:

for y in range(len(bord)):
    for x in range(len(bord[y])):
        print(bord[y][x])

此实例中的range()函数从0..len(board) - 1创建一个数组,所以假设bord的大小为5个元素,我们将执行range(5)。这与做for x in [0, 1, 2, 3, 4]相同。因此它迭代该数组并将当前元素保存在变量x中。

所以只是总结一下。

你可以这样做:

for y in bord:
    for x in y:
        print(x)

for y in range(len(bord)):
    for x in range(len(bord[y])):
        print(bord[y][x])

您可以使用任何一个,无论您喜欢哪个。使用其中一个可能是有原因但我不知道它,如果有人想编辑它以提供这个原因请做。

希望这有帮助!