iterator question
Steve Holden
steve at holdenweb.com
Tue Sep 26 15:02:44 EDT 2006
George Sakkis wrote:
> Neil Cerutti wrote:
>
>
>>On 2006-09-26, Neal Becker <ndbecker2 at gmail.com> wrote:
>>
>>>Any suggestions for transforming the sequence:
>>>
>>>[1, 2, 3, 4...]
>>>Where 1,2,3.. are it the ith item in an arbitrary sequence
>>>
>>>into a succession of tuples:
>>>
>>>[(1, 2), (3, 4)...]
>>>
>>>In other words, given a seq and an integer that specifies the
>>>size of tuple to return, then for example:
>>
>>It turns out there's a itertools recipe to do this; the last one
>>in the itertools recipe book:
>>
>>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)
>
>
> That's not quite the same as the previous suggestions; if the last
> tuple is shorter than n, it pads the last tuple with padvalue. The OP
> didn't mention if he wants that or he'd rather have a shorter last
> tuple.
>
In which case why not go in for a bit of requirements gold-plating and
add a keyword Boolean argument that allows you to specify which
behaviour you want. Or, alternatively, let the OP make sense of the
suggestions already made.
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden
More information about the Python-list
mailing list