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

2024-05-21 08:38:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个函数,它接收一个测试数据集,比较测试集中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

我尝试的嵌套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])])]

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


Tags: 函数inl1forlenreturndefnp