我有一个案例,我需要2个循环(i和k),如下所示。我想在离开之后继续使用内循环。
import numpy as np
X = [[12, 11, 1], [1,2,3]]
mu = [1, 2, 3]
sublist = []
for i in range(0, 4):
for k in range(0, 3):
subtr = X[i] - mu[k]
sublist.append(subtr)
# leaving the loop k to calc argmin
agmin = np.argmin(sublist)
C.append(agmin)
# Now I want to get back to the inner loop (k) to continue #further calculation, but obviously will result an error.
np.dot((C[i] == k),X[i])
处理此类案件的最佳方法是什么?
答案 0 :(得分:2)
在离开内循环之前,在内循环中做你需要做的一切。以下是您的代码的略微修改版本:
import numpy as np
X = [[12, 11, 1], [1,2,3]]
mu = [1, 2, 3]
sublist = []
C = #whatever C should be initialized to
for i in range(0, 4):
for k in range(0, 3):
subtr = X[i] - mu[k]
sublist.append(subtr)
# calculate agmin (argmin) once per inner loop, at end
if k == 2:
agmin = np.argmin(sublist)
C.append(agmin)
# not sure what this line does, but do it inside the inner loop since it
# needs k. (I'm guessing you really want some_var = np.dot(...) )
np.dot((C[i] == k),X[i])