Using enumerate to get line-numbers with itertools grouper?
Terry Reedy
tjreedy at udel.edu
Wed Sep 2 13:48:31 EDT 2015
On 9/2/2015 6:04 AM, Victor Hooi wrote:
> I'm using grouper() to iterate over a textfile in groups of lines:
>
> def grouper(iterable, n, fillvalue=None):
> "Collect data into fixed-length chunks or blocks"
> # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
> args = [iter(iterable)] * n
> return zip_longest(fillvalue=fillvalue, *args)
>
> However, I'd also like to know the line-number that I'm up to, for printing out in informational or error messages.
>
> Is there a way to use enumerate with grouper to achieve this?
Without a runnable test example, it is hard to be sure what you want.
However, I believe replacing 'iter(iterable)' with 'enumerate(iterable,
1)', and taking into account that you will get (line_number, line)
tuples instead of lines, will do what you want.
--
Terry Jan Reedy
More information about the Python-list
mailing list