给指定列表做拆分操作:
将一个大列表拆分成若干个指定长度的小列表;
举例:
原始列表: [1, 2, 3, 4, 5, 6] 拆分条件: 场景一: 拆成长度为2; --->拆分后列表: [[1, 2], [3, 4], [5, 6]] 场景二: 拆成长度为4; --->拆分后列表: [[1, 2, 3, 4], [5, 6]]
代码实现:
def cut_list(lists, cut_len):
res_data = []
if len(lists) > cut_len:
for i in range(int(len(lists) / cut_len)):
cut_a = lists[cut_len * i:cut_len * (i + 1)]
res_data.append(cut_a)
last_data = lists[int(len(lists) / cut_len) * cut_len:]
if last_data:
res_data.append(last_data)
else:
res_data.append(lists)
return res_data
# 将一个大列表拆分成若干个指定长度的小列表
test = [1, 2, 3, 4, 5, 6]
cut = 2
res = cut_list(test,cut)
print(res)
# [[1, 2], [3, 4], [5, 6]]
随手记,需要自取~~~


![[Python]列表操作:将一个大列表拆分成若干个指定长度的小列表 [Python]列表操作:将一个大列表拆分成若干个指定长度的小列表](http://www.mshxw.com/aiimages/31/929516.png)
