如何用单个函数替换两个for循环

时间:2018-01-22 16:48:08

标签: python loops refactoring

是否可以使用单个函数替换下面的for循环,同时仍然生成字典输出?唯一的区别是X_train,y_train和X_test以及y_test。什么是最好的方式?

for _ in range(batch_count):
    rand_index = np.random.choice(len(X_train), size=config.batch_size)
    batch_X = X_train[rand_index].reshape((1, config.num_steps, config.input_size))
    batch_y = y_train[rand_index].reshape((1, config.num_steps, config.output_size)) 

    '''Each loop below completes one epoch training.'''

    train_data_feed = {inputs: batch_X, targets: batch_y, learning_rate: 0.0}



for _ in range(batch_count):
    rand_index = np.random.choice(len(X_train), size=config.batch_size)
    batch_X = X_test[rand_index].reshape((1, config.num_steps, config.input_size))
    batch_y = y_test[rand_index].reshape((1, config.num_steps, config.output_size)) 

    test_data_feed = {inputs: batch_X, targets: batch_y, learning_rate: 0.0}

1 个答案:

答案 0 :(得分:2)

你要求其他人为你做一个重构......这不是一个问题..

您可以创建一个名为reshape_data(x,y)的方法,它可以执行for循环:

def reshape_data(x, y, other parameters needed):
    for _ in range(batch_count):
        rand_index = np.random.choice(len(X_train), size=config.batch_size)
        batch_X = x[rand_index].reshape((1, config.num_steps, config.input_size))
        batch_y = y[rand_index].reshape((1, config.num_steps, config.output_size))

然后你可以从主代码中调用它:

reshape_data(X_train, y_train, batch_count, config)
reshape_data(X_test, y_test, batch_count, config)

当然,你可以进一步重构它。

PD:没有测试代码,它不起作用,因为变量的范围是config和batch_count等。