I have a set of records coming back from the database in the following form:
data = [
["date", "value1a", "value2a", "value3a", ...],
["date", "value1b", "value2b", "value3b", ...]
]
I want to turn that set of rows into a list like
[
[("date", "value1a"), ("date", "value1b"), ... ],
[("date", "value2a"), ("date", "value2b"), ... ]
]
I know zip()
does this sort of thing, but I'm not clear on how to get the date into each record (and make them tuples). The length of the rows coming back from the database will not always be the same, but I will know the expected length in each call.
data = [["date_a", "1a", "2a", "3a"],
["date_b", "1b", "2b", "3b"]]
print zip(*(zip(itertools.repeat(ls[0]), ls[1:]) for ls in data))
gives
[(('date_a', '1a'), ('date_b', '1b')),
(('date_a', '2a'), ('date_b', '2b')),
(('date_a', '3a'), ('date_b', '3b'))]
See comments for some useful variations.
Use itertools repeat for the first element:
zip(itertools.repeat(ls[0]), ls[1:])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With