Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, zip multiple lists where one list requires two items each

Tags:

python

list

I have the following lists as an example:

a = ['#12908069', '#12906115', '#12904949', '#12904654', '#12904288', '#12903553']    
b = ['85028,', '83646,', '77015,', '90011,', '91902,', '80203,']    
c = ['9.09', '9.09', '1.81', '3.62', '1.81', '1.81', '9.09', '9.09', '1.81', '3.62', '1.81', '1.81']    
d = ['Zone 3', 'Zone 3', 'Zone 2']

What I'd like to achieve as an output, the first item set zipped as an example:

[('#12908069', '85028', (9.09, 9.09), 'Zone 3'), ...]

How do I get zip() to add an extra item for each tuple from list c?

like image 910
Kenny Powers Avatar asked Feb 06 '16 23:02

Kenny Powers


3 Answers

you can use list slices with a step of 2, see Explain Python's slice notation:

list(zip(a,b,zip(c[0::2],c[1::2]),d))
like image 73
Jacques Supcik Avatar answered Nov 15 '22 21:11

Jacques Supcik


using an idiom for clustering a data series into n-length groups from the zip documentation:

>>> gr = [iter(c)]*2
>>> list(zip(a, b, zip(*gr), d))
[('#12908069', '85028,', ('9.09', '9.09'), 'Zone 3'),
 ('#12906115', '83646,', ('1.81', '3.62'), 'Zone 3'),
 ('#12904949', '77015,', ('1.81', '1.81'), 'Zone 2')]

essentially, in order to get two consecutive elements from list c we put the same iterator on it in the gr list, which is made of two elements.

Then we pass those same iterators to zip (unpacking the list, as if we had passed the two iterators as two separate arguments to it).

That has the effect of collecting each two consecutive elements from list c.

We then pass such zip and the other lists to zip again to scan and pair the whole lot.

like image 38
Pynchia Avatar answered Nov 15 '22 22:11

Pynchia


Using one of the recipes from itertools:

>>> from itertools import zip_longest
>>> 
>>> def grouper(iterable, n, fillvalue=None):
...     "Collect data into fixed-length chunks or blocks"
...     # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
...     args = [iter(iterable)] * n
...     return zip_longest(*args, fillvalue=fillvalue)
... 
>>> list(zip(a, b, grouper(c, 2), d))
[('#12908069', '85028,', ('9.09', '9.09'), 'Zone 3'), ('#12906115', '83646,', ('1.81', '3.62'), 'Zone 3'), ('#12904949', '77015,', ('1.81', '1.81'), 'Zone 2')]
like image 42
Eugene Yarmash Avatar answered Nov 15 '22 22:11

Eugene Yarmash