Home > OS >  How to split a list into equal chuncks of a minimum size each?
How to split a list into equal chuncks of a minimum size each?

Time:10-01

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 list into the last group. Is that possible (knowing that I will consider those numbers for further operations)?

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:

lst = [0,1,2,3,4,5,6,7,8,9]
templist=[]
ctr1=0
x = len(lst)
print ("x",x)
for i in range (int (len(lst)/3)):
    for n in lst[ctr1:3  ctr1]:
        print ("hello")
        templist.append(n)
    #print (templist)
    print (x)
    y= x-3
    print ("y",y)
    if y<3 and y % 3: 
        templist.extend(lst[ctr1:])
        print ("yes")
    print (templist)
    #for n in lst[ctr1:3  ctr1]:
        #templist.append(n)
    ctr1 =3
    x=x-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:

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
if len(lst) % 3:
    templist.extend(lst[ctr1:])


print (templist)

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.

Explanation of code: The modulo operator (%) returns the remainder of a division operation. So len(lst) % 3 basically does 10/3 and only gives us the remainder (in this case, 1). The entire statement if len(lst) % 3 basically say "if there is anything left over, as a remainder, of dividing 10 into three chunks. lst[ctr1:] In this part of the code, we know that ctr1 holds the value of the last item in the group of three (9 in this case), because that was the last increment in the for loop. So we can use ctr1 and slicing to grab everything from where ctr1 left off to the end of the list. I used extend rather than append because append would give us a sub-list in the list, but the rest of your code is just returning a list and I assumed you wanted the structure to match. If you wanted the remaining items as a sub-list of your templist, just change extend to append.

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