Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zip multiple values with single value

Tags:

python

list

I have a list:

ave=['Avg']

and another one:

range(0,24)

How do I zip them so I will have:

[0,'Avg',1,'Avg',....23,'Avg']

It is preferred not to have each entry in brackets ie

[[0,'Avg'],[...]]

since I would later want to make that list into a CSV.

I know I could do it with a simple loop, but is there a more clean-cut way? a function maybe?

like image 972
maininformer Avatar asked Dec 02 '22 19:12

maininformer


2 Answers

I think a loop like this is clean enough:

ave=['Avg']
lst = []
for x in range(24):
    lst.extend((x,ave[0]))

lst:

>>> lst
[0, 'Avg', 1, 'Avg', 2, 'Avg', 3, 'Avg', 4, 'Avg', 5, 'Avg', 6, 'Avg', 7, 'Avg', 8, 'Avg', 9, 'Avg', 10, 'Avg', 11, 'Avg', 12, 'Avg', 13, 'Avg', 14, 'Avg', 15, 'Avg', 16, 'Avg', 17, 'Avg', 18, 'Avg', 19, 'Avg', 20, 'Avg', 21, 'Avg', 22, 'Avg', 23, 'Avg']
like image 99
timgeb Avatar answered Dec 05 '22 09:12

timgeb


It's easy enough to get the pairings as you noted, but you can then use itertools.chain() to unwrap the pairings:

from itertools import chain

fields = ['Avg']
indexes = range(0, 24)

groups = [[i] + fields for i in indexes]

flat_list = list(chain.from_iterable(groups))
like image 32
Platinum Azure Avatar answered Dec 05 '22 09:12

Platinum Azure