基本上,我想从给定列表l
中创建一个无限生成器,其批量大小为batch_size
。举例来说,如果我有l = [1, 2, 3, 4, 5]
和batch_size = 2
名单,我想产生的[1, 2]
,[3, 4]
,[5, 1]
,[2, 3]
无限循环......(类似于itertool.circular使用附加批量大小)从列表中生成循环批次
我目前的做法是因为在结束后不给予正确的解决方案还没有我只是垫列表的第一个元素,当我到达终点:
l = [1, 2, 3, 4, 5]
def generator(l, batch_size=2):
while 1:
for i in range(0, len(l), batch_size):
batch = l[i:(i + batch_size)]
if len(batch) < batch_size:
batch.extend(l[0: batch_size - len(batch)])
yield batch
>> gen = generator(l, batch_size=2)
>> next(gen) # [1, 2]
>> next(gen) # [3, 4]
>> next(gen) # [5, 1]
>> next(gen) # [1, 2] << want [2, 3] instead
有没有办法做到这一点以循环方式?
为什么分配给'x' ... –
@MosesKoledoye没有好的重新不久,我可以删除它 –
谢谢@ juanpa.arrivillaga!这很好地工作(在接受解决方案之前必须5分钟)。 – titipata