There are a number of solutions, as your question was a bit ambiguous about what you wanted, here are the solutions I would suggest.
Whatever you want, the first step is to split the list into independent lists. The cleanest way to do this is with a generator (there are other ways of doing this for generators as opposed to lists, but for your use case that's overkill):
def segments(l, n):
for i in range(0, len(l), n): #Use xrange in python 2.x
yield l[i:i+n]
Although it's entirely possible to use a generator expression, it isn't particularly readable:
(data[y:y+3] for y in range(0, len(data), 3))
Wherever I use segments(data, 3)
, you could use this generator expression instead, but I'll stick to the more readable version.
If you wanted output of matched (month, year, value)
, then the answer is very simple:
list(zip(*segments(data, 3)) #No need to use list() in 2.x
Produces:
[('January', 2007, 'value1'), ('Febraury', 2008, 'value2'), ('March', 2009, 'value3')]
We unpack our three lists as arguments into zip()
which gives us a generator of (month, year, value)
items.
If you wanted all of the combinations of (month, year, value)
then you can use itertools.product()
:
from itertools import product
...
list(product(*segments(data, 3))
If you only wanted, as your output suggests, the set product of the month tied to the value and the year, then you will need:
from itertools import product
...
months, years, values = segments(data, 3)
[(month, year, value) for ((month, value), year) in product(zip(months, values), years)]