【问题标题】:How do I iterate over two ranges whilst keeping one the same?如何在保持一个相同的同时迭代两个范围?
【发布时间】:2021-12-04 11:13:06
【问题描述】:

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

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

theta 是一维数组,X 是一个二维数组。我尝试使用这样的 for 循环,但我不知道如何首先为 theta[0]*X[i][0] 运行所有 i,然后为 theta[1]*X[i][1] 运行 i 等等。

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

【问题讨论】:

  • 请使用一致的变量名。首先是X[i],然后是X[j],然后for i in range(i) 超级混乱。
  • 加法顺序有区别吗?我问是因为首先你写theta[0]*X[i][0] + theta[1]*X[i][1] + ...,然后你暗示theta[0]*X[i][0] + theta[0]*X[i+1][0] + ...
  • 顺便说一句,欢迎来到 Stack Overflow!如果需要提示,请查看tourHow to Ask

标签: python loops iterator


【解决方案1】:

你想用 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)))

【讨论】:

  • sum(map(operator.mul, theta, x[i])),或更明确地说,sum(t*xi for t, xi in zip(theta, x[i]))
  • 谢谢,这正是我所需要的
猜你喜欢
  • 1970-01-01
  • 2011-10-10
  • 1970-01-01
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
  • 2018-02-25
  • 1970-01-01
  • 2023-01-12
相关资源
最近更新 更多