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?
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.
[tuple(list1[i:i+500]+['data']) for i in xrange(0, len(list1), 500)]
You can change 500 and expand it for any fragment size
A function that provides your output
def chunks_with_data(l, n):
return [tuple(l[i:i + n])+("data",) for i in range(0, len(l), n)]
>>>chunks_with_data(range(1000), 500)
But it can be very long!
base_lst = [x for x in range(1, 1001)]
lst = [tuple(base_lst[x:x+500]+['Data']) for x in range(500)]
print(lst)
Here is my question on this issue. It returns 500 items from list ( [(1...500),(501...1000)]
) and adds data
:
l = [x for x in range(1, 1001)]
out_l = [tuple(l[i:i+500] + ['data']) for i in xrange(0, len(l), 500)]