Iterate over a python sequence in multiples of n?

后端 未结 17 725
北荒
北荒 2020-12-01 17:45

How do I process the elements of a sequence in batches, idiomatically?

For example, with the sequence \"abcdef\" and a batch size of 2, I would like to do something

17条回答
  •  温柔的废话
    2020-12-01 18:22

    And then there's always the documentation.

    def pairwise(iterable):
        "s -> (s0,s1), (s1,s2), (s2, s3), ..."
        a, b = tee(iterable)
        try:
            b.next()
        except StopIteration:
            pass
        return izip(a, b)
    
    def grouper(n, iterable, padvalue=None):
        "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
        return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)
    

    Note: these produce tuples instead of substrings, when given a string sequence as input.

提交回复
热议问题