将一个长列表分为N个短列表
def Equal_division_list(eq_list, n):
'''
:param seq:传入的列表
:param n:划分的份数,几等分
:return:返回一个嵌套列表
'''
num_list = []
if n > len(eq_list):
print('份数大于列表长度,请重新输入')
elif n == 1:
num_list = eq_list
elif n == len(eq_list):
for i in eq_list:
num_list.append(i)
elif len(eq_list) % n == 0:
index = 0
for i in range(n):
num_list.append(eq_list[index:index + int(len(eq_list) / n)])
index += int(len(eq_list) / n)
else:
index = 0
for i in range(n):
num_list.append(eq_list[index:index + int(len(eq_list) / n)])
index += int(len(eq_list) / n)
for j in range(len(eq_list) % n):
num_list[-(j + 1)].append(eq_list[-(j + 1)])
return num_list
运行
if __name__ == '__main__':
print(Equal_division_list([i for i in range(5)], 4))
[[0], [1], [2], [3, 4]]
------------------------------------------------------------
if __name__ == '__main__':
print(Equal_division_list([i for i in range(15)], 4))
[[0, 1, 2], [3, 4, 5, 12], [6, 7, 8, 13], [9, 10, 11, 14]]