从外部循环回到内部for循环 - Python嵌套循环

时间:2017-06-16 22:58:11

标签: python for-loop nested

我有一个案例,我需要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])    

处理此类案件的最佳方法是什么?

1 个答案:

答案 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])