Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using zip() to rotate a list

Tags:

python

list

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.

like image 745
Tom Avatar asked Feb 20 '23 10:02

Tom


2 Answers

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.

like image 131
Janne Karila Avatar answered Feb 25 '23 17:02

Janne Karila


Use itertools repeat for the first element:

zip(itertools.repeat(ls[0]), ls[1:])