如何迭代两个范围同时保持一个相同?

How do I iterate over two ranges whilst keeping one the same?

我想迭代这个带有参数 theta、X 和 i 的函数。

hypothesis = theta[0]*X[i][0] + theta[1]*X[i][1] + theta[2]*X[i][2] + ...

theta 是一维数组,X 是二维数组。我试过像这样使用 for 循环,但我不确定如何先 运行 通过所有 i for theta[0]*X[i][0] 然后 运行 通过 i for theta[1]*X[i][1] 等等。

for i in range(i):
    for j in range(j):
        hypothesis += theta[i]*X[j][i]

你想用 X 的第 i 行做 theta 的点积吗?

如果是这样,那么您可以这样做:

def dot_product(theta, x, i):
  hypothesis = 0
  for j in range(len(theta)):
    hypothesis += theta[j] * x[i][j]
  return hypothesis

或者您可以通过 Python 的生成器功能使其更简洁:

def dot_product(theta, x, i):
  return sum(theta[j] * x[i][j] for j in range(len(theta)))