What is a simple way to use zip
to do:
Input: (1,2,3,4,5)
Output: ((1,2),(2,3),(3,4),(4,5))
Edit: yes, general ngram solutions are similar, but too verbose for such a simple task. See answers below to see why.
What is a simple way to use zip
to do:
Input: (1,2,3,4,5)
Output: ((1,2),(2,3),(3,4),(4,5))
Edit: yes, general ngram solutions are similar, but too verbose for such a simple task. See answers below to see why.
zip
the tuple with its own tail:
>>> ł = (1,2,3,4,5)
>>> zip(ł, ł[1:])
[(1, 2), (2, 3), (3, 4), (4, 5)]
You could initialize the tuple using a list comprehension or generator expression:
>>> x = (1, 2, 3 4, 5)
>>> tuple((x[i], x[i+1]) for i in range(len(x)-1))
((1, 2), (2, 3), (3, 4), (4, 5))
Or using slicing:
>>> tuple(x[i:i+2] for i in range(len(x)-1))
((1, 2), (2, 3), (3, 4), (4, 5))
in = (1, 2, 3, 4, 5)
out = tuple([(in[i], in[i+1] for i in range(len(in) - 1)])
print(out)
>> ((1, 2), (2, 3), (3, 4), (4, 5))
Another possibility
x = (1,2,3,4,5)
tuple([(a,b) for a,b in zip(x[:-1],x[1:])])