Python 3.x 以n Python的随机序列倍数迭代列表

Python 3.x 以n Python的随机序列倍数迭代列表,python-3.x,for-loop,random,Python 3.x,For Loop,Random,我有以下示例代码: l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def batch_gen(data, batch_size): for i in range(0, len(data), batch_size): yield data[i:i+batch_size] batch_size = randint(1,4) n = 0 print("batch_size is {}".format(batch_size)) for i in bat

我有以下示例代码:

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def batch_gen(data, batch_size):
    for i in range(0, len(data), batch_size):
        yield data[i:i+batch_size]
batch_size = randint(1,4)
n = 0
print("batch_size is {}".format(batch_size))
for i in batch_gen(l, batch_size):
    for x in i:
        print(x)
    print("loop {}".format(n))
    n += 1
    batch_size = randint(1,4)
这给了我以下的输出:

batch_size is 3
1
2
3
loop 0
4
5
6
loop 1
7
8
9
loop 2
10
loop 3
这是我正在寻找的输出,但是batch_size总是在for循环之外从batch_size=randint(1,4)设置

我希望为循环的每个迭代都有一个随机的批处理大小,并且每个下一个循环在最后一个循环停止的地方开始,直到完成一个随机长度列表

任何帮助都将不胜感激

示例代码取自