简体   繁体   English

来自itertools.cycle生成器的列表理解

[英]List comprehension from itertools.cycle generator

My problem was that I needed to deliver batches from an itertools.cycle generator in list form. 我的问题是我需要以清单形式从itertools.cycle生成器交付批次。

A cycle takes an iterable and loops it around itself indefinitely. 一个cycle需要一个可迭代的循环,并无限期地围绕自身循环。 For example: 例如:

>>> my_cycle = itertools.cycle('abc')
>>> next(my_cycle)
'a'
>>> next(my_cycle)
'b'
>>> next(my_cycle)
'c'
>>> next(my_cycle)
'a'

And so on. 等等。

The question becomes, how do we deliver a list of batch length n from a cyclic generator, while preserving where we are in the cycle? 问题就变成了,我们如何在保持我们在循环中的位置的同时,从循环发生器中获得批次长度n的列表?

Desired output is: 所需的输出是:

c = itertools.cycle('abc')
batch_size = 2
Out[0]: ['a', 'b']
Out[1]: ['c', 'a']
Out[2]: ['b', 'c']

I am posting my solution in case someone runs into the same problem. 如果有人遇到相同的问题,我会发布我的解决方案。

It seems like islice was made for this: 似乎isliceislice而制作的:

>>> from itertools import cycle, islice
>>> size_of_batch = 5
>>> c = cycle('abcdefg')
>>> list(islice(c, size_of_batch))
['a', 'b', 'c', 'd', 'e']
>>> list(islice(c, size_of_batch))
['f', 'g', 'a', 'b', 'c']
>>> size_of_batch = 5
>>> c = itertools.cycle('abcdefg')
>>> [next(c) for _ in range(size_of_batch)]

['a', 'b', 'c', 'd', 'e']

>>> [next(c) for _ in range(size_of_batch)]

['f', 'g', 'a', 'b', 'c']

There is an itertools recipe designed for this: 有一个为此设计的itertools配方

from itertools import islice, cycle


def take(n, iterable):
    "Return first n items of the iterable as a list"
    return list(islice(iterable, n))


c = cycle("abcdefg")
take(5, c)
# ['a', 'b', 'c', 'd', 'e']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM