Iterate over a string 2 (or n) characters at a time in Python

后端 未结 12 1878
悲哀的现实
悲哀的现实 2020-11-30 07:27

Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like \"+c-R+D-E\" (there are a few extra letters).

12条回答
  •  离开以前
    2020-11-30 08:07

    This approach support an arbitrary number of elements per result, evaluates lazily, and the input iterable can be a generator (no indexing is attempted):

    import itertools
    
    def groups_of_n(n, iterable):
        c = itertools.count()
        for _, gen in itertools.groupby(iterable, lambda x: c.next() / n):
            yield gen
    

    Any left-over elements are returned in a shorter list.

    Example usage:

    for g in groups_of_n(4, xrange(21)):
        print list(g)
    
    [0, 1, 2, 3]
    [4, 5, 6, 7]
    [8, 9, 10, 11]
    [12, 13, 14, 15]
    [16, 17, 18, 19]
    [20]
    

提交回复
热议问题