[Tutor] Python Idioms?
Mark Lawrence
breamoreboy at yahoo.co.uk
Wed Apr 1 16:19:11 CEST 2015
On 01/04/2015 14:16, Steven D'Aprano wrote:
> On Wed, Apr 01, 2015 at 12:06:33PM +0100, Mark Lawrence wrote:
>
>> In which case I'll stick with the more-itertools pairwise() function
>> which I pointed out on another thread just yesterday. From
>> http://pythonhosted.org//more-itertools/api.html
>>
>> <quote>
>> Returns an iterator of paired items, overlapping, from the original
>>
>>>>> take(4, pairwise(count()))
>> [(0, 1), (1, 2), (2, 3), (3, 4)]
>
> I betcha the implementation of pairwise is something really close to:
>
> def pairwise(iterable):
> it = iter(iterable)
> return itertools.izip(it, it)
>
> for Python 2, and for Python 3:
>
> def pairwise(iterable):
> it = iter(iterable)
> return zip(it, it)
>
Not a bad attempt :) It's actually.
def pairwise(iterable):
"""Returns an iterator of paired items, overlapping, from the original
>>> take(4, pairwise(count()))
[(0, 1), (1, 2), (2, 3), (3, 4)]
"""
a, b = tee(iterable)
next(b, None)
return zip(a, b)
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Tutor
mailing list