基本上,我想从给定列表l
创建一个无限生成器,其批量大小为batch_size
。例如,如果我有l = [1, 2, 3, 4, 5]
和batch_size = 2
的列表,我想生成[1, 2]
,[3, 4]
,[5, 1]
,{{1}的无限循环},...(类似于itertool.circular,具有额外的批量大小)
我目前的方法是下面的方法还没有给出正确的解决方案,因为最后我只是在到达结尾时填充列表的第一个元素:
[2, 3]
有没有办法以循环方式做到这一点?
答案 0 :(得分:4)
是的,您基本上想要“take”和cycle
:
>>> def circle_batch(iterable, batchsize):
... it = itertools.cycle(iterable)
... while True:
... yield list(itertools.islice(it, batchsize))
...
>>> l = [1, 2, 3, 4, 5]
>>> c = circle_batch(l, 2)
>>> next(c)
[1, 2]
>>> next(c)
[3, 4]
>>> next(c)
[5, 1]
>>> next(c)
[2, 3]
>>> next(c)
[4, 5]
从recipes in the docs您可以看到take
是一个基本工具,所以使用它:
>>> def take(n, iterable):
... "Return first n items of the iterable as a list"
... return list(islice(iterable, n))
...
>>> def cycle_batch(iterable, batchsize):
... it = itertools.cycle(iterable)
... while True:
... return take(batchsize, it)
...
>>> l = [1, 2, 3, 4, 5]
>>> c = circle_batch(l, 2)
>>> next(c)
[1, 2]
>>> next(c)
[3, 4]
>>> next(c)
[5, 1]
>>> next(c)
[2, 3]
>>> next(c)
[4, 5]
>>> next(c)
[1, 2]
答案 1 :(得分:3)
这应该有效:
enzyme-adapter-react-16