Split list into even chunks

Split list into even chunks

danispag
Enthusiast Enthusiast
1,036 Views
1 Reply
Message 1 of 2

Split list into even chunks

danispag
Enthusiast
Enthusiast

I have a list of objects and I need to split this list into chunks of 3 using the 'range' function.

Can it be done?

Thanks in advance

 

sel = cmds.ls(sl = 1)

halfSel = len(sel)/2

 

chunk_sep = []
for i in range (0,halfSel, 3):

chunk_sep.append([lst[i],lst[i+1],lst[i+2],lst[i+3],lst[i+4]])

0 Likes
1,037 Views
1 Reply
Reply (1)
Message 2 of 2

jmreinhart
Advisor
Advisor
sel = cmds.ls(sl = True)
num_elements_per_chunk = 3

sel = range(12)

result = []
for i in range(len(sel)/num_elements_per_chunk):
    if (i+1)*num_elements_per_chunk <= len(sel):
        result.append(sel[i*num_elements_per_chunk:(i+1)*num_elements_per_chunk])

print result

num_chunks = 6
chunk_length = len(sel)/num_chunks
result = []
for i in range(num_chunks):
    if (i+1)*chunk_length <= len(sel):
        result.append(sel[i*chunk_length:(i+1)*chunk_length])

print result

here are examples of how to split a list based on number of chunks or a specific chunks length

0 Likes