I am using the following function pairwise
to get the iteration of ordered pairs. For example, if the iterable is a list [1, 2, 3, 4, 5, 6]
then I want to get (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 1)
. If I use the following function
JavaScript
x
7
1
from itertools import tee, zip_longest
2
def pairwise(iterable):
3
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
4
a, b = tee(iterable)
5
next(b, None)
6
return zip_longest(a, b)
7
then it returns (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, None)
.
I am using dataloader
in my code as iterable, so I want to pass only iterable
as input to the function pairwise
and I don’t want to pass extra inputs.
How do I get the first element as the last element in the last item as mentioned above?
Advertisement
Answer
zip_longest
has fillvalue
parameter
JavaScript
1
2
1
return zip_longest(a, b, fillvalue=iterable[0])
2
or as suggested in the comments use the returned value of the next(b, None)
in fillvalue
JavaScript
1
4
1
def pairwise(iterable):
2
a, b = tee(iterable)
3
return zip_longest(a, b, fillvalue=next(b, None))
4
Output
JavaScript
1
2
1
print(list(pairwise(lst))) # [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 1)]
2
You can also do it without converting the list to iterators
JavaScript
1
3
1
def pairwise(iterable):
2
return zip_longest(iterable, iterable[1:], fillvalue=iterable[0])
3