【问题标题】:What is the most "pythonic" way to iterate over a list in chunks?以块为单位迭代列表的最“pythonic”方式是什么?
【发布时间】:2010-09-30 20:41:12
【问题描述】:

我有一个 Python 脚本,它以整数列表作为输入,我需要一次处理四个整数。不幸的是,我无法控制输入,否则我会将其作为四元素元组列表传入。目前,我正在以这种方式对其进行迭代:

for i in range(0, len(ints), 4):
    # dummy op for example code
    foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3]

不过,它看起来很像“C-think”,这让我怀疑有一种更 Pythonic 的方式来处理这种情况。该列表在迭代后被丢弃,因此不需要保留。也许这样的事情会更好?

while ints:
    foo += ints[0] * ints[1] + ints[2] * ints[3]
    ints[0:4] = []

不过,仍然不太“感觉”正确。 :-/

相关问题:How do you split a list into evenly sized chunks in Python?

【问题讨论】:

  • 如果列表大小不是四的倍数,您的代码将不起作用。
  • 我正在扩展()列表,以便它的长度是四的倍数,然后才能达到这个程度。
  • @ΤZΩΤZΙΟΥ — 问题非常相似,但并不完全重复。它是“分成任意数量的大小为 N 的块”与“分成任意大小的 N 块”。 :-)

标签: python list loops optimization chunks


【解决方案1】:
def chunker(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq), size))
# (in python 2 use xrange() instead of range() to avoid allocating a list)

适用于任何序列:

text = "I am a very, very helpful text"

for group in chunker(text, 7):
   print(repr(group),)
# 'I am a ' 'very, v' 'ery hel' 'pful te' 'xt'

print '|'.join(chunker(text, 10))
# I am a ver|y, very he|lpful text

animals = ['cat', 'dog', 'rabbit', 'duck', 'bird', 'cow', 'gnu', 'fish']

for group in chunker(animals, 3):
    print(group)
# ['cat', 'dog', 'rabbit']
# ['duck', 'bird', 'cow']
# ['gnu', 'fish']

【讨论】:

  • @Carlos Crasborn 的版本适用于任何可迭代对象(不仅仅是上面代码中的序列);它很简洁,可能同样快甚至更快。虽然对于不熟悉 itertools 模块的人来说可能有点晦涩(不清楚)。
  • 请注意,chunker 返回一个generator。将返回替换为:return [...] 以获取列表。
  • 除了编写函数构建然后返回生成器,您还可以直接编写生成器,使用yield:for pos in xrange(0, len(seq), size): yield seq[pos:pos + size]。我不确定在内部这是否会在任何相关方面有任何不同的处理,但它可能会更清楚一点。
  • 请注意,这仅适用于支持按索引访问项目的序列,不适用于通用迭代器,因为它们可能不支持 __getitem__ 方法。
  • @smci 上面的chunker() 函数是一个生成器 - 它返回一个生成器表达式
【解决方案2】:

修改自 Python 的 itertools 文档的 Recipes 部分:

from itertools import zip_longest

def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

示例

grouper('ABCDEFG', 3, 'x')  # --> 'ABC' 'DEF' 'Gxx'

注意:在 Python 2 上使用 izip_longest 而不是 zip_longest

【讨论】:

  • 终于有机会在 python 会话中玩弄这个了。对于那些和我一样困惑的人来说,这是多次向 izip_longest 提供相同的迭代器,导致它消耗相同序列的连续值,而不是来自不同序列的条带值。我喜欢它!
  • 过滤掉填充值的最佳方法是什么? ([item for item in items if item is not fillvalue] for items in grouper(iterable))?
  • 我怀疑这个石斑鱼配方对于 256k 大小的块的性能会很差,因为 izip_longest 将被提供 256k 参数。
  • 在几个地方,评论者说“当我终于弄清楚这是如何工作的时......”也许需要一些解释。特别是迭代器列表方面。
  • 有没有办法使用这个但没有None 填满最后一个块?
【解决方案3】:
chunk_size = 4
for i in range(0, len(ints), chunk_size):
    chunk = ints[i:i+chunk_size]
    # process chunk of size <= chunk_size

【讨论】:

  • 如果 len(ints) 不是 chunkSize 的倍数,它的行为如何?
  • @AnnaVopureta chunk 最后一批元素将有 1、2 或 3 个元素。请参阅有关为什么slice indices can be out of bounds 的这个问题。
【解决方案4】:
import itertools
def chunks(iterable,size):
    it = iter(iterable)
    chunk = tuple(itertools.islice(it,size))
    while chunk:
        yield chunk
        chunk = tuple(itertools.islice(it,size))

# though this will throw ValueError if the length of ints
# isn't a multiple of four:
for x1,x2,x3,x4 in chunks(ints,4):
    foo += x1 + x2 + x3 + x4

for chunk in chunks(ints,4):
    foo += sum(chunk)

另一种方式:

import itertools
def chunks2(iterable,size,filler=None):
    it = itertools.chain(iterable,itertools.repeat(filler,size-1))
    chunk = tuple(itertools.islice(it,size))
    while len(chunk) == size:
        yield chunk
        chunk = tuple(itertools.islice(it,size))

# x2, x3 and x4 could get the value 0 if the length is not
# a multiple of 4.
for x1,x2,x3,x4 in chunks2(ints,4,0):
    foo += x1 + x2 + x3 + x4

【讨论】:

  • +1 用于使用生成器,接缝就像所有建议的解决方案中最“pythonic”一样
  • 对于如此简单的事情来说,它相当冗长且笨拙,根本不是很pythonic。我更喜欢 S. Lott 的版本
  • @zenazn:这将适用于生成器实例,切片不会
  • 除了与生成器和其他不可切片的迭代器一起正常工作外,如果最终块小于size,第一个解决方案也不需要“填充”值,这有时是可取的.
  • 对于生成器也是 +1。其他解决方案需要len 调用,因此不适用于其他生成器。
【解决方案5】:

如果您不介意使用外部软件包,您可以使用来自iteration_utilties 1iteration_utilities.grouper。它支持所有的可迭代对象(不仅仅是序列):

from iteration_utilities import grouper
seq = list(range(20))
for group in grouper(seq, 4):
    print(group)

哪个打印:

(0, 1, 2, 3)
(4, 5, 6, 7)
(8, 9, 10, 11)
(12, 13, 14, 15)
(16, 17, 18, 19)

如果长度不是分组大小的倍数,它还支持填充(不完整的最后一组)或截断(丢弃不完整的最后一组)最后一个:

from iteration_utilities import grouper
seq = list(range(17))
for group in grouper(seq, 4):
    print(group)
# (0, 1, 2, 3)
# (4, 5, 6, 7)
# (8, 9, 10, 11)
# (12, 13, 14, 15)
# (16,)

for group in grouper(seq, 4, fillvalue=None):
    print(group)
# (0, 1, 2, 3)
# (4, 5, 6, 7)
# (8, 9, 10, 11)
# (12, 13, 14, 15)
# (16, None, None, None)

for group in grouper(seq, 4, truncate=True):
    print(group)
# (0, 1, 2, 3)
# (4, 5, 6, 7)
# (8, 9, 10, 11)
# (12, 13, 14, 15)

基准

我还决定比较一些上述方法的运行时间。这是一个对数图,根据不同大小的列表分组为“10”个元素组。对于定性结果:越低意味着越快:

至少在这个基准测试中iteration_utilities.grouper 表现最好。其次是Craz的方法。

基准是使用simple_benchmark1 创建的。用于运行此基准测试的代码是:

import iteration_utilities
import itertools
from itertools import zip_longest

def consume_all(it):
    return iteration_utilities.consume(it, None)

import simple_benchmark
b = simple_benchmark.BenchmarkBuilder()

@b.add_function()
def grouper(l, n):
    return consume_all(iteration_utilities.grouper(l, n))

def Craz_inner(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

@b.add_function()
def Craz(iterable, n, fillvalue=None):
    return consume_all(Craz_inner(iterable, n, fillvalue))

def nosklo_inner(seq, size):
    return (seq[pos:pos + size] for pos in range(0, len(seq), size))

@b.add_function()
def nosklo(seq, size):
    return consume_all(nosklo_inner(seq, size))

def SLott_inner(ints, chunk_size):
    for i in range(0, len(ints), chunk_size):
        yield ints[i:i+chunk_size]

@b.add_function()
def SLott(ints, chunk_size):
    return consume_all(SLott_inner(ints, chunk_size))

def MarkusJarderot1_inner(iterable,size):
    it = iter(iterable)
    chunk = tuple(itertools.islice(it,size))
    while chunk:
        yield chunk
        chunk = tuple(itertools.islice(it,size))

@b.add_function()
def MarkusJarderot1(iterable,size):
    return consume_all(MarkusJarderot1_inner(iterable,size))

def MarkusJarderot2_inner(iterable,size,filler=None):
    it = itertools.chain(iterable,itertools.repeat(filler,size-1))
    chunk = tuple(itertools.islice(it,size))
    while len(chunk) == size:
        yield chunk
        chunk = tuple(itertools.islice(it,size))

@b.add_function()
def MarkusJarderot2(iterable,size):
    return consume_all(MarkusJarderot2_inner(iterable,size))

@b.add_arguments()
def argument_provider():
    for exp in range(2, 20):
        size = 2**exp
        yield size, simple_benchmark.MultiArgument([[0] * size, 10])

r = b.run()

1 免责声明:我是库iteration_utilitiessimple_benchmark 的作者。

【讨论】:

    【解决方案6】:

    我需要一个同样适用于集合和生成器的解决方案。我想不出任何非常简短和漂亮的东西,但至少它的可读性很强。

    def chunker(seq, size):
        res = []
        for el in seq:
            res.append(el)
            if len(res) == size:
                yield res
                res = []
        if res:
            yield res
    

    列表:

    >>> list(chunker([i for i in range(10)], 3))
    [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
    

    设置:

    >>> list(chunker(set([i for i in range(10)]), 3))
    [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
    

    生成器:

    >>> list(chunker((i for i in range(10)), 3))
    [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
    

    【讨论】:

      【解决方案7】:

      more-itertools 包有 chunked 方法,它正是这样做的:

      import more_itertools
      for s in more_itertools.chunked(range(9), 4):
          print(s)
      

      打印

      [0, 1, 2, 3]
      [4, 5, 6, 7]
      [8]
      

      chunked 返回列表中的项目。如果您更喜欢迭代,请使用ichunked

      【讨论】:

        【解决方案8】:

        此问题的理想解决方案适用于迭代器(不仅仅是序列)。它也应该很快。

        这是itertools的文档提供的解决方案:

        def grouper(n, iterable, fillvalue=None):
            #"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
            args = [iter(iterable)] * n
            return itertools.izip_longest(fillvalue=fillvalue, *args)
        

        在我的 mac book air 上使用 ipython 的 %timeit,每个循环我得到 47.5 us。

        但是,这对我来说真的不起作用,因为结果被填充为均匀大小的组。没有填充的解决方案稍微复杂一些。最天真的解决方案可能是:

        def grouper(size, iterable):
            i = iter(iterable)
            while True:
                out = []
                try:
                    for _ in range(size):
                        out.append(i.next())
                except StopIteration:
                    yield out
                    break
                
                yield out
        

        简单,但相当慢:每个循环 693 us

        我能想到的最佳解决方案是使用 islice 进行内部循环:

        def grouper(size, iterable):
            it = iter(iterable)
            while True:
                group = tuple(itertools.islice(it, None, size))
                if not group:
                    break
                yield group
        

        使用相同的数据集,每个循环我得到 305 us。

        无法比这更快地获得纯解决方案,我提供以下解决方案并提出重要警告:如果您的输入数据中有 filldata 的实例,您可能会得到错误的答案。

        def grouper(n, iterable, fillvalue=None):
            #"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
            args = [iter(iterable)] * n
            # itertools.zip_longest on Python 3
            for x in itertools.izip_longest(*args, fillvalue=fillvalue):
                if x[-1] is fillvalue:
                    yield tuple(v for v in x if v is not fillvalue)
                else:
                    yield x
        

        我真的不喜欢这个答案,但它明显更快。每个循环 124 我们

        【讨论】:

        • 您可以通过将配方 #3 移至 C 层将其运行时间减少约 10-15%(省略 itertools 导入;map 必须是 Py3 mapimap) :def grouper(n, it): return takewhile(bool, map(tuple, starmap(islice, repeat((iter(it), n)))))。使用哨兵可以使您的最终函数变得不那么脆弱:去掉fillvalue 参数;添加第一行fillvalue = object(),然后将if 检查更改为if i[-1] is fillvalue:,并将其控制的行更改为yield tuple(v for v in i if v is not fillvalue)。保证iterable 中的任何值都不会被误认为是填充值。
        • 顺便说一句,对#4 大赞。我正要发布我对 #3 的优化,作为比迄今为止发布的更好的答案(性能方面),但是通过调整使其可靠、有弹性的 #4 运行速度是优化 #3 的两倍;我没想到一个带有 Python 级别循环(并且没有理论上的算法差异 AFAICT)的解决方案会获胜。我假设 #3 由于构造/迭代 islice 对象的费用而失败(如果 n 相对较大,则 #3 获胜,例如组的数量很少,但这是针对不常见情况进行优化的),但我没有预计它会非常极端。
        • 对于#4,条件的第一个分支只在最后一次迭代(最终的元组)中出现。与其重新构建最终的元组,不如在顶部缓存原始迭代长度的模,并使用它在最终元组izip_longest 上切掉不需要的填充:yield i[:modulo]。此外,对于args 变量,将它作为一个元组而不是一个列表:args = (iter(iterable),) * n。减少了几个时钟周期。最后,如果我们忽略填充值并假设None,则条件可以变为if None in i,持续更多时钟周期。
        • @Kumba:您的第一个建议假设输入的长度已知。如果它是一个迭代器/生成器,而不是一个已知长度的集合,则没有什么可以缓存的。无论如何,没有真正的理由使用这种优化。您正在优化不常见的情况(最后一个yield),而常见的情况不受影响。
        【解决方案9】:
        from itertools import izip_longest
        
        def chunker(iterable, chunksize, filler):
            return izip_longest(*[iter(iterable)]*chunksize, fillvalue=filler)
        

        【讨论】:

        【解决方案10】:

        在 Python 3.8 中,您可以使用 walrus 运算符和 itertools.islice

        from itertools import islice
        
        list_ = [i for i in range(10, 100)]
        
        def chunker(it, size):
            iterator = iter(it)
            while chunk := list(islice(iterator, size)):
                print(chunk)
        
        In [2]: chunker(list_, 10)                                                         
        [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
        [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
        [30, 31, 32, 33, 34, 35, 36, 37, 38, 39]
        [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
        [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
        [60, 61, 62, 63, 64, 65, 66, 67, 68, 69]
        [70, 71, 72, 73, 74, 75, 76, 77, 78, 79]
        [80, 81, 82, 83, 84, 85, 86, 87, 88, 89]
        [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
        
        

        【讨论】:

          【解决方案11】:

          与其他提案类似,但不完全相同,我喜欢这样做,因为它简单易读:

          it = iter([1, 2, 3, 4, 5, 6, 7, 8, 9])
          for chunk in zip(it, it, it, it):
              print chunk
          
          >>> (1, 2, 3, 4)
          >>> (5, 6, 7, 8)
          

          这样你就不会得到最后的部分块。如果您想将(9, None, None, None) 作为最后一个块,只需使用itertools 中的izip_longest

          【讨论】:

          • 可以用zip(*([it]*4))改进
          • @Jean-François Fabre:从可读性的角度来看,我不认为这是一种改进。而且它也稍微慢了一点。如果你在打高尔夫球,这是一种进步,而我不是。
          • 不,我不是在打高尔夫球,但是如果你有 10 个参数呢?我在一些官方页面上阅读了该结构。但当然我现在似乎找不到它:)
          • @Jean-François Fabre:如果我有 10 个参数或可变数量的参数,这是一个选项,但我宁愿写:zip(*(it,)*10)跨度>
          • 对! 那是我读到的。不是我编的清单:)
          【解决方案12】:

          由于没有人提到它,这里有一个zip() 解决方案:

          >>> def chunker(iterable, chunksize):
          ...     return zip(*[iter(iterable)]*chunksize)
          

          只有当你的序列长度总是能被块大小整除或者你不关心尾随块时它才有效。

          例子:

          >>> s = '1234567890'
          >>> chunker(s, 3)
          [('1', '2', '3'), ('4', '5', '6'), ('7', '8', '9')]
          >>> chunker(s, 4)
          [('1', '2', '3', '4'), ('5', '6', '7', '8')]
          >>> chunker(s, 5)
          [('1', '2', '3', '4', '5'), ('6', '7', '8', '9', '0')]
          

          或者使用itertools.izip返回一个迭代器而不是一个列表:

          >>> from itertools import izip
          >>> def chunker(iterable, chunksize):
          ...     return izip(*[iter(iterable)]*chunksize)
          

          可以使用@ΤΖΩΤΖΙΟΥ's answer修复填充:

          >>> from itertools import chain, izip, repeat
          >>> def chunker(iterable, chunksize, fillvalue=None):
          ...     it   = chain(iterable, repeat(fillvalue, chunksize-1))
          ...     args = [it] * chunksize
          ...     return izip(*args)
          

          【讨论】:

            【解决方案13】:

            另一种方法是使用iter 的两个参数形式:

            from itertools import islice
            
            def group(it, size):
                it = iter(it)
                return iter(lambda: tuple(islice(it, size)), ())
            

            这可以很容易地适应使用填充(这类似于Markus Jarderot 的答案):

            from itertools import islice, chain, repeat
            
            def group_pad(it, size, pad=None):
                it = chain(iter(it), repeat(pad))
                return iter(lambda: tuple(islice(it, size)), (pad,) * size)
            

            这些甚至可以组合成可选的填充:

            _no_pad = object()
            def group(it, size, pad=_no_pad):
                if pad == _no_pad:
                    it = iter(it)
                    sentinel = ()
                else:
                    it = chain(iter(it), repeat(pad))
                    sentinel = (pad,) * size
                return iter(lambda: tuple(islice(it, size)), sentinel)
            

            【讨论】:

            • 首选,因为您可以选择省略填充!
            【解决方案14】:

            使用 map() 而不是 zip() 修复了 J.F. Sebastian 回答中的填充问题:

            >>> def chunker(iterable, chunksize):
            ...   return map(None,*[iter(iterable)]*chunksize)
            

            例子:

            >>> s = '1234567890'
            >>> chunker(s, 3)
            [('1', '2', '3'), ('4', '5', '6'), ('7', '8', '9'), ('0', None, None)]
            >>> chunker(s, 4)
            [('1', '2', '3', '4'), ('5', '6', '7', '8'), ('9', '0', None, None)]
            >>> chunker(s, 5)
            [('1', '2', '3', '4', '5'), ('6', '7', '8', '9', '0')]
            

            【讨论】:

            • 这最好用itertools.izip_longest (Py2)/itertools.zip_longest (Py3); map 的这种使用是双重弃用的,并且在 Py3 中不可用(您不能将 None 作为映射器函数传递,并且它会在最短的迭代用尽时停止,而不是最长的迭代;它不填充) .
            【解决方案15】:

            如果列表很大,执行此操作的最佳方法是使用生成器:

            def get_chunk(iterable, chunk_size):
                result = []
                for item in iterable:
                    result.append(item)
                    if len(result) == chunk_size:
                        yield tuple(result)
                        result = []
                if len(result) > 0:
                    yield tuple(result)
            
            for x in get_chunk([1,2,3,4,5,6,7,8,9,10], 3):
                print x
            
            (1, 2, 3)
            (4, 5, 6)
            (7, 8, 9)
            (10,)
            

            【讨论】:

            • (我认为 MizardX 的 itertools 建议在功能上与此等价。)
            • (实际上,经过反思,不,我没有。itertools.islice 返回一个迭代器,但它不使用现有的。)
            • 它既好又简单,但由于某种原因,即使没有转换为元组,也比 iterable = range(100000000)chunksize 上接受的 grouper 方法慢 4-7 倍,最高可达 10000。
            • 但是,总的来说我会推荐这种方法,因为当检查最后一项很慢时,接受的方法可能会非常慢docs.python.org/3/library/itertools.html#itertools.zip_longest
            【解决方案16】:

            使用小功能和东西真的不吸引我;我更喜欢只使用切片:

            data = [...]
            chunk_size = 10000 # or whatever
            chunks = [data[i:i+chunk_size] for i in xrange(0,len(data),chunk_size)]
            for chunk in chunks:
                ...
            

            【讨论】:

            • 很好,但对于没有已知len 的无限流来说没有好处。您可以使用itertools.repeatitertools.cycle 进行测试。
            • 另外,因为使用[...for...] list comprehension 来物理构建列表而不是使用(...for...) generator expression 会占用内存,这只会关心下一个元素和备用内存
            【解决方案17】:

            为避免所有转换为列表import itertools 和:

            >>> for k, g in itertools.groupby(xrange(35), lambda x: x/10):
            ...     list(g)
            

            生产:

            ... 
            0 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
            1 [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
            2 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
            3 [30, 31, 32, 33, 34]
            >>> 
            

            我检查了groupby,它没有转换为列表或使用len,所以我(认为)这会延迟每个值的解析,直到它被实际使用。遗憾的是(目前)似乎没有可用的答案提供这种变化。

            显然,如果您需要依次处理每个项目,则在 g 上嵌套一个 for 循环:

            for k,g in itertools.groupby(xrange(35), lambda x: x/10):
                for i in g:
                   # do what you need to do with individual items
                # now do what you need to do with the whole group
            

            我对此的特别兴趣是需要使用生成器以将最多 1000 个批次的更改提交到 gmail API:

                messages = a_generator_which_would_not_be_smart_as_a_list
                for idx, batch in groupby(messages, lambda x: x/1000):
                    batch_request = BatchHttpRequest()
                    for message in batch:
                        batch_request.add(self.service.users().messages().modify(userId='me', id=message['id'], body=msg_labels))
                    http = httplib2.Http()
                    self.credentials.authorize(http)
                    batch_request.execute(http=http)
            

            【讨论】:

            • 如果您要分块的列表不是升序整数序列怎么办?
            • @PaulMcGuire 见groupby;给定一个描述 order 的函数,那么 iterable 的元素可以是任何东西,对吧?
            • 是的,我对 groupby 很熟悉。但是如果消息是字母“ABCDEFG”,那么groupby(messages, lambda x: x/3) 会给你一个 TypeError(试图用一个整数除一个字符串),而不是 3 个字母的分组。现在,如果你做了groupby(enumerate(messages), lambda x: x[0]/3),你可能会有所收获。但你没有在帖子中这么说。
            【解决方案18】:

            4 大小的块迭代列表x 的单线、临时解决方案-

            for a, b, c, d in zip(x[0::4], x[1::4], x[2::4], x[3::4]):
                ... do something with a, b, c and d ...
            

            【讨论】:

              【解决方案19】:

              使用 NumPy 很简单:

              ints = array([1, 2, 3, 4, 5, 6, 7, 8])
              for int1, int2 in ints.reshape(-1, 2):
                  print(int1, int2)
              

              输出:

              1 2
              3 4
              5 6
              7 8
              

              【讨论】:

                【解决方案20】:
                def chunker(iterable, n):
                    """Yield iterable in chunk sizes.
                
                    >>> chunks = chunker('ABCDEF', n=4)
                    >>> chunks.next()
                    ['A', 'B', 'C', 'D']
                    >>> chunks.next()
                    ['E', 'F']
                    """
                    it = iter(iterable)
                    while True:
                        chunk = []
                        for i in range(n):
                            try:
                                chunk.append(next(it))
                            except StopIteration:
                                yield chunk
                                raise StopIteration
                        yield chunk
                
                if __name__ == '__main__':
                    import doctest
                
                    doctest.testmod()
                

                【讨论】:

                  【解决方案21】:

                  除非我错过了什么,否则没有提到以下使用生成器表达式的简单解决方案。它假定 块的大小和数量都是已知的(通常是这种情况),并且不需要填充:

                  def chunks(it, n, m):
                      """Make an iterator over m first chunks of size n.
                      """
                      it = iter(it)
                      # Chunks are presented as tuples.
                      return (tuple(next(it) for _ in range(n)) for _ in range(m))
                  

                  【讨论】:

                    【解决方案22】:

                    在你的第二种方法中,我会通过这样做进入下一组 4 人:

                    ints = ints[4:]
                    

                    但是,我没有进行任何性能测量,所以我不知道哪一个可能更有效。

                    话虽如此,我通常会选择第一种方法。它并不漂亮,但这通常是与外界交互的结果。

                    【讨论】:

                      【解决方案23】:

                      又一个答案,其优点是:

                      1) 易于理解
                      2) 适用于任何可迭代的,而不仅仅是序列(上面的一些答案会阻塞文件句柄)
                      3) 不会一次将块全部加载到内存中
                      4) 不在内存中创建对同一迭代器的引用的大块列表
                      5) 列表末尾没有填充值的填充

                      话虽如此,我还没有计时,所以它可能比一些更聪明的方法慢,而且考虑到用例,一些优点可能无关紧要。

                      def chunkiter(iterable, size):
                        def inneriter(first, iterator, size):
                          yield first
                          for _ in xrange(size - 1): 
                            yield iterator.next()
                        it = iter(iterable)
                        while True:
                          yield inneriter(it.next(), it, size)
                      
                      In [2]: i = chunkiter('abcdefgh', 3)
                      In [3]: for ii in i:                                                
                                for c in ii:
                                  print c,
                                print ''
                              ...:     
                              a b c 
                              d e f 
                              g h 
                      

                      更新:
                      由于内部和外部循环从同一个迭代器中提取值,因此存在一些缺点:
                      1) continue 在外循环中不能按预期工作 - 它只是继续到下一个项目而不是跳过一个块。但是,这似乎不是问题,因为在外循环中没有要测试的内容。
                      2) break 在内部循环中没有按预期工作 - 控制将再次在内循环中结束,迭代器中的下一个项目。要跳过整个块,请将内部迭代器(上面的 ii)包装在一个元组中,例如for c in tuple(ii),或者设置一个标志并耗尽迭代器。

                      【讨论】:

                        【解决方案24】:
                        def group_by(iterable, size):
                            """Group an iterable into lists that don't exceed the size given.
                        
                            >>> group_by([1,2,3,4,5], 2)
                            [[1, 2], [3, 4], [5]]
                        
                            """
                            sublist = []
                        
                            for index, item in enumerate(iterable):
                                if index > 0 and index % size == 0:
                                    yield sublist
                                    sublist = []
                        
                                sublist.append(item)
                        
                            if sublist:
                                yield sublist
                        

                        【讨论】:

                        • +1 它省略了填充;你的和 bcoughlan's 很相似
                        【解决方案25】:

                        您可以使用 funcy 库中的 partitionchunks 函数:

                        from funcy import partition
                        
                        for a, b, c, d in partition(4, ints):
                            foo += a * b * c * d
                        

                        这些函数还有迭代器版本ipartitionichunks,在这种情况下效率会更高。

                        你也可以偷看their implementation

                        【讨论】:

                          【解决方案26】:

                          关于J.F. Sebastianhere给出的解决方案:

                          def chunker(iterable, chunksize):
                              return zip(*[iter(iterable)]*chunksize)
                          

                          它很聪明,但有一个缺点——总是返回元组。如何获取字符串?
                          当然你可以写''.join(chunker(...)),但是临时元组还是要构造的。

                          您可以通过编写自己的zip 来摆脱临时元组,如下所示:

                          class IteratorExhausted(Exception):
                              pass
                          
                          def translate_StopIteration(iterable, to=IteratorExhausted):
                              for i in iterable:
                                  yield i
                              raise to # StopIteration would get ignored because this is generator,
                                       # but custom exception can leave the generator.
                          
                          def custom_zip(*iterables, reductor=tuple):
                              iterators = tuple(map(translate_StopIteration, iterables))
                              while True:
                                  try:
                                      yield reductor(next(i) for i in iterators)
                                  except IteratorExhausted: # when any of iterators get exhausted.
                                      break
                          

                          然后

                          def chunker(data, size, reductor=tuple):
                              return custom_zip(*[iter(data)]*size, reductor=reductor)
                          

                          示例用法:

                          >>> for i in chunker('12345', 2):
                          ...     print(repr(i))
                          ...
                          ('1', '2')
                          ('3', '4')
                          >>> for i in chunker('12345', 2, ''.join):
                          ...     print(repr(i))
                          ...
                          '12'
                          '34'
                          

                          【讨论】:

                          • 不是要你改变答案的批评,而是评论:代码是一种责任。您编写的代码越多,您为隐藏错误创建的空间就越多。从这个角度来看,重写zip而不是使用现有的似乎不是最好的主意。
                          【解决方案27】:

                          我喜欢这种方法。它感觉简单而不神奇,并且支持所有可迭代类型并且不需要导入。

                          def chunk_iter(iterable, chunk_size):
                          it = iter(iterable)
                          while True:
                              chunk = tuple(next(it) for _ in range(chunk_size))
                              if not chunk:
                                  break
                              yield chunk
                          

                          【讨论】:

                            【解决方案28】:

                            这里很pythonic(你也可以内联split_groups函数的主体)

                            import itertools
                            def split_groups(iter_in, group_size):
                                return ((x for _, x in item) for _, item in itertools.groupby(enumerate(iter_in), key=lambda x: x[0] // group_size))
                            
                            for x, y, z, w in split_groups(range(16), 4):
                                foo += x * y + z * w
                            

                            【讨论】:

                              【解决方案29】:

                              我从不希望我的块被填充,所以这个要求是必不可少的。我发现处理任何迭代的能力也是必需的。鉴于此,我决定扩展已接受的答案https://stackoverflow.com/a/434411/1074659

                              如果由于需要比较和过滤填充值而不需要填充,则此方法的性能会受到轻微影响。但是,对于大块大小,此实用程序非常高效。

                              #!/usr/bin/env python3
                              from itertools import zip_longest
                              
                              
                              _UNDEFINED = object()
                              
                              
                              def chunker(iterable, chunksize, fillvalue=_UNDEFINED):
                                  """
                                  Collect data into chunks and optionally pad it.
                              
                                  Performance worsens as `chunksize` approaches 1.
                              
                                  Inspired by:
                                      https://docs.python.org/3/library/itertools.html#itertools-recipes
                              
                                  """
                                  args = [iter(iterable)] * chunksize
                                  chunks = zip_longest(*args, fillvalue=fillvalue)
                                  yield from (
                                      filter(lambda val: val is not _UNDEFINED, chunk)
                                      if chunk[-1] is _UNDEFINED
                                      else chunk
                                      for chunk in chunks
                                  ) if fillvalue is _UNDEFINED else chunks
                              

                              【讨论】:

                                【解决方案30】:

                                这是一个没有导入支持生成器的分块器:

                                def chunks(seq, size):
                                    it = iter(seq)
                                    while True:
                                        ret = tuple(next(it) for _ in range(size))
                                        if len(ret) == size:
                                            yield ret
                                        else:
                                            raise StopIteration()
                                

                                使用示例:

                                >>> def foo():
                                ...     i = 0
                                ...     while True:
                                ...         i += 1
                                ...         yield i
                                ...
                                >>> c = chunks(foo(), 3)
                                >>> c.next()
                                (1, 2, 3)
                                >>> c.next()
                                (4, 5, 6)
                                >>> list(chunks('abcdefg', 2))
                                [('a', 'b'), ('c', 'd'), ('e', 'f')]
                                

                                【讨论】:

                                  猜你喜欢
                                  • 2015-09-11
                                  • 2019-08-18
                                  • 2012-04-16
                                  • 2017-12-16
                                  • 1970-01-01
                                  相关资源
                                  最近更新 更多