首页 > 解决方案 > Python for 循环从 2 个数据集中获取 n 行

问题描述

我想每次使用 zip() 从 x_train 和 y_train 中获取 n 行。所以下面的代码是我试图做的。在每次迭代中,我更新上一个批次和下一个批次,所以我将从两个 2d numpy 数组中获得 [0-5],[5-10],... 行。

batch_size = 3
next_b = batch_size
prev_b = 0

//sample input
x_train = [ [0,1,2],[3,4,5],[6,7,8],[9,10,11],[12,13,14] ]
y_train = [ [3],[6],[9],[12],[15] ]    

for X,y in zip(x_train,y_train)[prev_b:next_b]:
    print(X,y)

    //prev_b = 0, next_b = 3, so i want to get below values at first iter
    //X => [[0,1,2],[3,4,5],[6,7,8]]
    //y => [ [3],[6],[9] ]

    prev_b = next_b //-> prev_b = 3, for the next iteration
    next_b += batch_size //-> next_b = 6, for the next iteration

欢迎任何帮助。

标签: python-3.xnumpy-ndarraypython-zip

解决方案


在这里,只需使用正确定义的索引对列表进行切片:

x_train = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14]]
y_train = [[3], [6], [9], [12], [15]]
batch_size = 3

for loop_number, start in enumerate(range(0, len(x_train), batch_size)):
    print(f"loop {loop_number}")
    end = start + batch_size
    X = x_train[start:end]
    y = y_train[start:end]
    print(f"X equals {X}")
    print(f"y equals {y}\n")

结果:

loop 0
X equals [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
y equals [[3], [6], [9]]

loop 1
X equals [[9, 10, 11], [12, 13, 14]]
y equals [[12], [15]]

推荐阅读