How do I create an ordered list of 500 tuples and then add data to it?
This is my code using Python 2.7
list1 = [1,2,3,4,5,6,9,10.....1000]
I am trying to create chunks of 500 list data like
chunk_data = [(1,2,3,4,5,...500),(501,502....1000)]
and then I am going to add "data" at the end of each chunk
so it looks like this:
[(1,2...500,'data'),(501,502...1000,'data')]
I tried using zip for this
it = iter(list1)
chunked_data = zip(*[it]*500)
but i can't add "data" now
from itertools import repeat
chunked_data = zip(*[it]*500,repeat("data")) #Gives Error about adding arguments after unpacking function values !!
I was unable to write this code below, although it will work
chunked_data = zip(it,it,it...(500 times),repeat("data")]
So how do I go about doing this?
+3
source to share
5 answers
You can create a list of positional arguments and then unpack it:
args = [it] * 500 + [repeat('data')]
chunked_data = zip(*args)
This is essentially a modified grouper
recipe from the documentation itertools
.
This works great:
In [17]: it = iter('0123456789')
In [18]: args = [it] * 5 + [repeat('data')]
In [19]: list(zip(*args))
Out[19]: [('0', '1', '2', '3', '4', 'data'), ('5', '6', '7', '8', '9', 'data')]
Alternative solution:
[tuple(list1[i:i+500]) + ('data',) for i in range(0, len(list1), 500)]
More information can be found on the page.
+3
source to share