Python for 循环从 2 个数据集中获取 n 行

Python for loop get n rows from 2 datasets

我想每次使用 zip() 在 for 循环中从 x_train 和 y_train 获取 n 行。所以下面的代码是我尝试 do.At 每次迭代我更新上一批和下一批所以我将从两个 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

欢迎任何帮助。

给你,用正确定义的索引切片你的列表:

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]]