首页 > 解决方案 > 如何将列表拆分为每个最小大小的相等块?

问题描述

这将追加 0、1、2,然后是 3、4、5,然后是 6、7、8。虽然我需要它来追加 0、1、2,然后是 3、4、5,然后是 6、7、8、9。我需要它将列表的全部内容考虑到最后一组。这可能吗(知道我会考虑这些数字以进行进一步的操作)?

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)

标签: python-3.xlist

解决方案


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)

推荐阅读