自己写的import mathdef split_list(alist, split_len): # TODO: 是否有改进之处 """ 按照每4个一组进行划分 :param alist: :param split_len: :return: """ b = [] start_split_index = 0 length = int(math.ceil(len(alist) / float(split_len))) while length > 0: a = [] end_index = start_split_index + split_len for i in alist[start_split_index:end_index]: a.append(i) start_split_index += split_len length -= 1 b.append(a) return b 网上看到的def list_of_groups(init_list, children_list_len): list_of_group = zip(*(iter(init_list),) * children_list_len) end_list = [list(i) for i in list_of_group] count = len(init_list) % children_list_len end_list.append(init_list[-count:]) if count != 0 else end_list return end_list CookBookdef slice_list(seq, size): return [seq[i:i + size] for i in range(0, len(seq), size)] def zip_iter(seq, size): # TODO:没看懂,这个方法当 seq 太小时,会返回空;e.g.zip_iter(list(range(2)),4) return list(zip(*[iter(seq)] * size)) 执行结果if __name__ == '__main__': a = list(range(24)) num = 4 t1 = split_list(a, num) t2 = list_of_groups(a, num) t3 = slice_list(a, num) t4 = zip_iter(a, num) print(t1) print(t2) print(t3) print(t4)# [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]# [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]# [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]# [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15), (16, 17, 18, 19), (20, 21, 22, 23)] 更多阅读 Splitting A Python List Into Sublists split a list into roughly equal-sized pieces (python recipe) Python | Split list into lists by particular value 文章作者: imoyao文章链接: https://masantu.com/blog/2019-12-27/python-split-list-into-lists-by-particular-value/版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 别院牧志!PythonTODO深深别院,潜潜牧志上一篇Hexo 主题 Butterfly 自定义之路下一篇OpenStack 开发记录 相关推荐 2020-01-12使用 Python 压缩图片(借助 TinyPng 的接口) 2019-05-11MySQL 中存储 IP 地址应该选用何种数据类型? 2020-04-19🐍PyTricks | Python 中如何合并一个内字典列表? 2020-04-15中国传统色 | 如何判断一个颜色属于什么色系? 2020-04-13中国传统色 | 朱砂痣还是白月光,哪个才是我们的心头好? 2020-05-10不问色号 | 口红色号获取之烈艳蓝金系列 评论