python 等分 整数 列表
作者:互联网
# 拆分整数
def split_integer(m, n):
assert n > 0
flag = 1
if m < 0 :
flag = -1
quotient = (m*flag) //n #int(m / n)
remainder = (m*flag) % n
if remainder: #如果有余数
return [(quotient + 1)*flag] * remainder + [quotient*flag] * (n - remainder)
else: #没有余数,整除
return [quotient*flag] * n
#list 等分 n 组
def divide_list(lst,n):
#如果等分的组数为小于等于1或者超出list长度则直接返回当前lst作为一组
if n <=1 or n>len(lst):
yield lst
return
div = split_integer(len(lst), n) #等分list,每组元素个数
start=0
for i in div:
end = start + i
yield lst[start:end]
start = end
for ilist in divide_list([1,2,3,4,5,6],5):
print(ilist)
标签:python,list,lst,整数,列表,start,flag,remainder,quotient 来源: https://www.cnblogs.com/bitterain/p/12881470.html