Python 使用for循环内联与嵌套for循环

Python 使用for循环内联与嵌套for循环,python,nearest-neighbor,Python,Nearest Neighbor,我正在开发一个函数,该函数接收测试数据集,比较测试集中62个点与训练集中248个点的差异,确定哪个训练数据点最接近,并使用该索引返回预测输出的数组 我使函数如下图所示工作,但无法使用嵌套for循环使其工作。有人能解释一下为什么嵌套for循环的工作方式不同吗?我是python新手,我已经为此奋斗了一段时间 def distance(x,y): return np.sum(np.abs(x-y)) def NN_L1(trainx, trainy, testx): # inputs

我正在开发一个函数,该函数接收测试数据集,比较测试集中62个点与训练集中248个点的差异,确定哪个训练数据点最接近,并使用该索引返回预测输出的数组

我使函数如下图所示工作,但无法使用嵌套for循环使其工作。有人能解释一下为什么嵌套for循环的工作方式不同吗?我是python新手,我已经为此奋斗了一段时间

def distance(x,y):
    return np.sum(np.abs(x-y))

def NN_L1(trainx, trainy, testx):
    # inputs: trainx, trainy, testx <-- as defined above
    # output: an np.array of the predicted values for testy 

    ### BEGIN SOLUTION
    predictions_l1 = np.ones(62)
    for j in range(len(testx)):
        prediction = trainy[np.argmin([distance(testx[j],trainx[i]) for i in range(len(trainx))])]
        predictions_l1[j] = prediction
    return predictions_l1

当我完成函数时,我总是得到一个相同值的数组

如果您试图更改
test\u 1
,则在嵌套for循环中不引用它。如果您试图更改
test\u 1
,则在嵌套for循环中不引用它。
test_1 = np.ones(62)
for j in range(len(testx)):
    for i in range(len(trainx)):
        tester = trainy[np.argmin([distance(testx[j], trainx[i])])]