gpt4 book ai didi

For loops using "cell" in Python, Index problem [closed](对于在Python中使用“cell”的循环,索引问题[已关闭])

转载 作者:bug小助手 更新时间:2023-10-25 22:22:22 25 4
gpt4 key购买 nike




code
When I try to travel through a 2D array,and to record the (i,j) pairs that I want, I find that the index function always return the same j in each different loop. I think in each loop, "cell" should be different, even though they likely to have the same value.Really confused.

code当我尝试遍历一个2D数组,并记录我想要的(i,j)对时,我发现index函数在每个不同的循环中总是返回相同的j。我认为在每个循环中,“cell”应该是不同的,即使它们可能具有相同的值。真的很困惑。


code
Like I said, you can see that instead of a [(0,0),(0,1),(0,2),...], the result is in the picture above.

代码就像我说的,你可以看到不是[(0,0),(0,1),(0,2),.],结果如上图所示。


更多回答
优秀答案推荐

index is the wrong tool here. Remember that index always returns the FIRST match. If you have several occurrences of 0, it's only going to return the index of the first one.

在这里,索引是错误的工具。请记住,索引总是返回第一个匹配项。如果有几次出现0,它只会返回第一次的索引。


You need to use enumerate, so you track the indexes as well as the contents:

您需要使用ENUMERATE,因此您可以跟踪索引和内容:


for y,row in enumerate(board):
for x,cell in enumerate(row):
if cell == EMPTY:
actions.append( (y, x) )


arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

pairs = []
for i in range(len(arr)):
for j in range(len(arr[i])):
pairs.append((i, j))

print(pairs)

Output: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]


I hope this meets your need

我希望这能满足你的需要


更多回答

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com