Home > Mobile >  This is different than the posted questions: how to split a list into equal chuncks of a minimum siz
This is different than the posted questions: how to split a list into equal chuncks of a minimum siz

Time:09-30

This will append 0,1,2 then 3,4,5 then 6,7,8. While I need it to append 0,1,2 then 3,4,5 then 6,7,8,9. I need it to consider the whole contents of the lst into the last group. Is that possible (Knowing that I will consider those numbers for further operations) ? Thanks in advance!

lst = [0,1,2,3,4,5,6,7,8,9]
templist=[]
ctr1=0
for i in range (int (len(lst)/3)):
  for n in lst[ctr1:3  ctr1]:
    templist.append(n)
  ctr1 =3

print (templist)

CodePudding user response:

It's not clear to me exactly what you're trying to accomplish, so maybe this won't help you, but you can just add a check outside the for loop to see if there are remaining items in list:

if len(lst) % 3:
    templist.extend(lst[ctr1:])

But you say you want equal chunks of a minimum size, but isn't that 2 instead of 3? Or do you mean the minimum number of chunks that are of an equal size? That would be 4.

CodePudding user response:

lst = [0,1,2,3,4,5,6,7,8,9]
templist=[]
ctr1=0
v = int (len(lst)/3)
for i in range (v):
  if i!= v-1:
    for n in lst[ctr1:3  ctr1]:
      templist.append(n)
  if i==v -1:
    for n in lst[ctr1:]:
      templist.append(n)
  print (templist)
  ctr1 =3
  • Related