Python, zip multiple lists in which one list requires two elements

As an example, I have the following lists:

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 would like to receive as an output, the first element put as an example:

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

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

+5
source share
4 answers

you can use list fragments in step 2, see Explain Python fragment notation :

 list(zip(a,b,zip(c[0::2],c[1::2]),d)) 
+9
source

using the idiom to cluster 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, to get two consecutive elements from the list c , we put the same iterator on it in the gr list, which consists of two elements.

Then we pass the same iterators to zip (unpack the list as if we passed two iterators as two separate arguments).

This leads to the collection of each of two consecutive elements from the list c .

Then we pass such a zip and other lists in order to re-scan again and join the entire batch.

+5
source

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')] 
+2
source

Try using the following code:

 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'] result = list(zip(a, b, [(c[i*2],c[i*2+1]) for i in range(len(c)//2)], d)) print(result) 
0
source

Source: https://habr.com/ru/post/1242457/


All Articles