在Python中按指定长度拆分列表

云课堂学Python 2025-02-19 22:28:50
Python 列表是用于存储有序元素的可变的数据类型,拆分列表是 Python 中的一项常见任务。本文中将介绍按指定长度拆分列表的多种方法。 例如: 列表 lst = [1, 2, 3, 4, 5, 6],指定查分长度: N。 N=2,输出[[1, 2], [3, 4], [5, 6]] N=3,输出[[1, 2, 3], [4, 5, 6]] 方法1:列表推导式列表推导式是创建新列表的简洁而强大的方法。允许在一行代码中转换或过滤列表的元素,可用于拆分列表。 lst = [1, 2, 3, 4, 5, 6, 7]n = 2chunks = [lst[i:i+n] for i in range(0, len(lst), n)]print(chunks)方法2:itertools 模块itertools 模块的 islice 方法可用于拆分列表,通过指定大小对列表进行切片来创建较小的列表。 from itertools import islicelst = [1, 2, 3, 4, 5, 6, 7]n = 2it = iter(lst) # 创建迭代器chunks = [list(islice(it, n)) for _ in range(0, len(lst), n)]print(chunks) 方法3:使用 for 循环简单的方法是使用 For 循环利用列表切片进行拆分,此方法易于实现,也易于理解。 lst = [1, 2, 3, 4, 5, 6, 7]n = 3chunks = []for i in range(0, len(lst), n): chunks.append(lst[i:i+n])print(chunks)
0 阅读:2