laszlopanaflex laszlopanaflex - 4 months ago 25
Python Question

Concatenating element pairs of a list sequentially

I am wondering what the pythonic way to accomplish the following would be. Suppose I have a list:

days = ['m', 't', 'w', 'r', 'f', 's', 's']

I would like to obtain a list which would look like:

['t-m', 'w-t', 'r-w', 'f-r', 's-f', 's-s']

so it would have to treat the original list as an iterator and move in order to perform the concatenation.

I would think this could be accomplished through some sort of list comprehension and use of the
function, but no luck in my attempts so far! I am using python 2.7.


Use zip() with a slice days[1:] and the original days, in a list comprehension, to iterate over a sliding window of reversed element pairs:

>>> days = ['m', 't', 'w', 'r', 'f', 's', 's']
>>> ['-'.join(pair) for pair in zip(days[1:], days)]
['t-m', 'w-t', 'r-w', 'f-r', 's-f', 's-s']