Python 3-不了解单行双循环

时间:2019-04-23 13:21:29

标签: python python-3.x for-loop

我正在查看以下功能:

# Initialize a network
def initialize_network(n_inputs, n_hidden, n_outputs):
    network = list()
    hidden_layer = [{'weights':[random() for i in range(n_inputs + 1)]} for i in range(n_hidden)]
    network.append(hidden_layer)
    output_layer = [{'weights':[random() for i in range(n_hidden + 1)]} for i in range(n_outputs)]
    network.append(output_layer)
    return network

但是,我特别受[{'weights':[random() for i in range(n_inputs + 1)]} for i in range(n_hidden)]这一行的困扰。我正在尝试将单行重新创建为函数:

def make_weights(n_inputs, n_hidden):
    # for i in range(n_inputs + 1):
        # make a random number?
    # for i in range(n_hidden):
        # make a random number?
    # return array of random numbers?

但是,我不太明白那一行在做什么。它遍历输入的数量+ 1次,并创建一个随机数吗?然后对隐藏输入的数量也做同样的事情吗?

我很困惑,我正在寻找一个人来帮助解释那条单线,并帮助将那条线映射到一个更简洁的函数中。

到目前为止使用的资源:

2 个答案:

答案 0 :(得分:3)

通常,以下两个是等效的:

result = [obj for sub in iterable for obj in sub]

# and

result = []
for sub in interable:
    for obj in sub:
        result.append(obj)

因此,您的make_weights函数可以定义如下:

def make_weights(n_inputs, n_hidden):
    result = []
    for i in range(n_hidden):
        weights = {'weights': []}
        for j in range(n_inputs + 1):
            weights['weights'].append(random())

        result.append(weights)

答案 1 :(得分:2)

等效的for循环可能如下,

results = []
for i in range(n_hidden):
        weights = {'weights': []}
        for j in range(n_inputs + 1):
            weights['weights'].append(random())
        result.append(weights)