替换重复的代码并在for循环中创建变量

2024-06-16 17:28:02 发布

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

我有这段代码可以预测模型,我觉得有一种方法可以编写for循环来缩短它。但是,我不太确定如何这样做,因为我必须在for循环中创建变量。是否可以将此代码缩短为for循环:

    #remainder1 through model

    _remainder1FV, _remainder1Out, _remainder1OutID = _detector.get_fv(_deFV, _deMeta['_remainID1'])
    _remainder1PredOut = _detector.classifer_prediction(_remainder1FV, _deMeta)
    _remainder1Result = _detector.result_calculation(_remainder1Out, _remainder1PredOut, _deMeta, tag='_remainID1')


    #remainder2 through model

    _remainder2FV, _remainder2Out, _remainder2OutID = _detector.get_fv(_deFV, _deMeta['_remainID2'])
    _remainder2PredOut = _detector.classifer_prediction(_remainder2FV, _deMeta)
    _remainder2Result = _detector.result_calculation(_remainder2Out, _remainder2PredOut, _deMeta, tag='_remainID2')


    #remainder3 through model

    _remainder3FV, _remainder3Out, _remainder3OutID = _detector.get_fv(_deFV, _deMeta['_remainID3'])
    _remainder3PredOut = _detector.classifer_prediction(_remainder3FV, _deMeta)
    _remainder3Result = _detector.result_calculation(_remainder3Out, _remainder3PredOut, _deMeta, tag='_remainID3')


    #remainder4 through model

    _remainder4FV, _remainder4Out, _remainder4OutID = _detector.get_fv(_deFV, _deMeta['_remainID4'])
    _remainder4PredOut = _detector.classifer_prediction(_remainder4FV, _deMeta)
    _remainder4Result = _detector.result_calculation(_remainder4Out, _remainder4PredOut, _deMeta, tag='_remainID4')

Tags: 代码forgetmodeltagresultdetectorprediction
2条回答

是的,我想这应该对你有用:)

_remainderResults = []
for i in ('_remainID1', '_remainID2', '_remainID3', '_remainID4'):
    _remainderFV, _remainderOut, _remainderOutID = _detector.get_fv(_deFV, _deMeta[i])
    _remainderPredOut = _detector.classifer_prediction(_remainderFV, _deMeta)
    _remainderResults.append(_detector.result_calculation(_remainderOut, _remainderPredOut, _deMeta, tag=i))

_remainder1Result, _remainder2Result, _remainder3Result, _remainder4Result = _remainderResults

你为什么不直接用字典来保存你的结果呢?你知道吗

results={};
for id in range(1,5):
    _remainderFV, _remainderOut, _remainderOutID = _detector.get_fv(_deFV, _deMeta['_remainID'+str(id)])
    _remainderPredOut = _detector.classifer_prediction(_remainderFV, _deMeta)
    _remainderResult = _detector.result_calculation(_remainderOut, _remainderPredOut, _deMeta, tag='_remainID'+str(id))
    results[id]=_remainderResult

相关问题 更多 >