简体   繁体   English

在 Python 的 for 循环中使用 range(len(x)) 时添加索引有什么影响? 例如范围(len(x [0])

[英]What is the effect of adding an index when using range(len(x)) in a for loop in Python? e.g. range(len(x[0])

I'm pretty new to coding, and am using Python.我对编码很陌生,并且正在使用 Python。 In an online lesson, I'm creating a minimax function to try and programme AI to play Connect 4. The following code makes up the evaluation function to tally whether player "X" and player "O" have any 'two streaks' (in one direction for now) by counting whether, given a position on the board, the piece in the column to its right, has the same symbol.在在线课程中,我正在创建一个 minimax function 来尝试对 AI 进行编程以玩 Connect 4。以下代码构成了评估 function 以计算玩家“X”和玩家“O”是否有任何“两条条纹”(在一个方向)通过计算,给定板上的 position,其右侧列中的部件是否具有相同的符号。

def my_evaluate_board(board):
  if has_won(board, "X"):
    return float("Inf")
  elif has_won(board, "O"):
    return -float("Inf")
  else:
    x_two_streak = 0
    o_two_streak = 0
    for col in range(len(board)-1):
      for row in range(len(board[0])):
        if board[col][row] == "X" and board[col + 1][row] == "X":
          x_two_streak += 1
    for col in range(len(board)-1):
      for row in range(len(board[0])):
        if board[col][row] == "O" and board[col + 1][row] == "O":
          o_two_streak += 1
    return x_two_streak - o_two_streak

I understand that in the for loop:我明白在 for 循环中:

for col in range(len(board)-1):

the -1 is in place because the code is looking to the right of each column to look for two pieces in a row and this prevents the loop from trying to look to the right of the final column. -1 就位是因为代码正在寻找每列的右侧以连续查找两个部分,这可以防止循环尝试查找最后一列的右侧。

What I don't understand is why the addition of an index in next line of code is doing what it is doing:我不明白为什么在下一行代码中添加索引正在做它正在做的事情:

for row in range(len(board[0])):

Elsewhere in my script, I've printed the output of this line, with and without the index, but no matter what index I put, I get the same result.在我的脚本的其他地方,我打印了这一行的 output,有无索引,但无论我放什么索引,我都会得到相同的结果。 The board has 7 columns, each with 6 rows.该板有 7 列,每列有 6 行。 See below:见下文:

print(range(len(new_board[0])))
# this returns: range(0, 6)

print(range(len(new_board)))
# this prints: range(0, 7)

and to demonstrate what I mean about the value of the index not making any difference:并证明我对指数价值没有任何影响的意思:

print(range(len(new_board[4])))
# this prints: range(0, 6)

I guess the purpose of this is to reduce the number of times the function loops through the rows by 1 because there is 1 less row than there are columns.我想这样做的目的是减少 function 循环通过行的次数 1,因为行比列少 1。

Please could someone explain why the addition of an index to the for loop makes the function behave this way?请有人解释为什么在 for 循环中添加索引会使 function 表现得这样吗?

looks like your data is organized as a matrix that is this case is implemented as a list of lists.看起来您的数据被组织为一个矩阵,在这种情况下,它被实现为一个列表列表。 This means that each element of board is a list representing a column.这意味着 board 的每个元素都是代表一列的列表。 The length of a column represents the number of rows of your matrix.列的长度表示矩阵的行数。 Each column will have the same length, so you can pick any of them to find the number of rows.每列将具有相同的长度,因此您可以选择其中任何一个来查找行数。 Best pick is the first column (the one with index [0]).最佳选择是第一列(索引为 [0] 的列)。

To be more clear you could use为了更清楚,你可以使用

n_cols = len(board)
n_rows = len(board[0])

and rewrite your loops as并将你的循环重写为

for row_index in range(n_rows):
    for column_index in range(n_cols):

Trying to understand better this structure you can create your own sample matrix尝试更好地理解这种结构,您可以创建自己的样本矩阵

l = [[1, 2, 3], [4, 5, 6]]

thus you created a matrix with shape 2x3因此您创建了一个形状为 2x3 的矩阵

print(len(l))

will return 2, while将返回 2,而

print(l[0])
print(l[1])

will return [1,2, 3] and [3, 4, 5].将返回 [1,2, 3] 和 [3, 4, 5]。 Each of them has length 3 (so print(len(l[0]) or print(len(l[1]) will both return 3). Even better way to visualize your matrix would be casting it to a numpy array它们每个的长度为 3(因此print(len(l[0])print(len(l[1])都将返回 3)。可视化矩阵的更好方法是将其转换为 numpy 数组

import numpy
print(numpy.array(l))

will show you the matrix in a more familiar shape将以更熟悉的形状向您展示矩阵

[[1 2 3]
 [2 3 4]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM