首页 > 解决方案 > 以可理解的形式重写 for 循环

问题描述

我想用另一种更容易理解的形式重写下面的python for循环。

def geo_margin(W,b,X,y):
    return np.min([margin(W,b, X,y[i])
                   for i, x in enumerate(X)])

标签: pythonfor-loop

解决方案


你的意思是这样吗?

import numpy as np

def geo_margin(W, b, X, y):
    data = []                  # Declare a list
    for i, x in enumerate(X):  # loop through X as index -> i and item -> x
        data.append(margin(W, b, X, y[i])) # Add the result of the function call to data

    return np.min(data) # return the minimum of the data

推荐阅读