【问题标题】:List comprehension from itertools.cycle generator来自 itertools.cycle 生成器的列表理解
【发布时间】:2018-08-11 08:22:28
【问题描述】:

我的问题是我需要从itertools.cycle 生成器以列表形式交付批次。

cycle 接受一个可迭代对象并无限期地围绕自身循环。例如:

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

等等。

问题变成了,我们如何从循环生成器中提供一个批处理长度列表n,同时保留我们在循环中的位置?

期望的输出是:

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

如果有人遇到同样的问题,我会发布我的解决方案。

【问题讨论】:

标签: python python-3.x itertools cycle


【解决方案1】:

似乎islice 就是为此而生的:

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

【讨论】:

    【解决方案2】:
    >>> 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']
    

    【讨论】:

      【解决方案3】:

      为此设计了一个itertools recipe

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

      【讨论】:

        猜你喜欢
        • 2013-12-30
        • 2021-04-07
        • 2016-10-04
        • 2023-02-02
        • 2017-08-05
        • 2016-07-09
        • 2018-04-20
        • 2016-02-06
        相关资源
        最近更新 更多