# 拆分整数
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
这篇文章介绍了如何使用Python编写函数split_integer,实现整数的等分,以及divide_list函数,将列表按照指定数量分成相等或接近的子列表。通过实例演示了如何处理整数除法、余数和列表切分的操作。
3292

被折叠的 条评论
为什么被折叠?



