I'm trying to chunk 100 lists from a nestled list. I have looked looked through multiple examples on Stack Overflow, but I still cannot get something working correctly.
My primary list is named data_to_insert and it contains other lists. I would like to extract (chunk) 100 lists from the primary nestled list.
How do I accomplish this?
This is my current code, which doesn't work as needed.
def divide_chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
n = 100
x = list(divide_chunks(data_to_insert, 100))
Nestled list example:
data_to_insert = [['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
...
[thousands of others lists go here]]
Desired output is another list (sliced_data), which contains 100 lists from the nestled list (data_to_insert).
sliced_data = [['item1','item2','item3','item4','item5','item6'],
['item1','item2','item3','item4','item5','item6'],
...
[98 more lists go here]]
I need to loop through the nestled list, data_to_insert until it's empty.
You can use random
to select 100
random nested lists from your given list.
This will output 3
random nested list from original list,
import random
l = [[1,2], [3,4], [1,1], [2,3], [3,5], [0,0]]
print(random.sample(l, 3))
# output,
[[3, 4], [1, 2], [2, 3]]
If you do not want a list output then replace print(random.sample(l, 3))
with print(*random.sample(l, 3))
,
# output,
[1, 2] [2, 3] [1, 1]
If you just want first 100
nested lists then do,
print(l[:100])