Python中如何按每次取5个元素的规则迭代遍历列表
Python列表按固定长度分块迭代实现方案
方案1:列表切片实现(全Python版本兼容)
这是兼容性最好的实现方式,不需要依赖任何第三方库或高版本语法:
L = ["a","b","c","d","e","f","g","h","i","j"] # 按步长5遍历列表索引 for idx in range(0, len(L), 5): # 每次取长度为5的切片 current_chunk = L[idx:idx+5] # 若需要过滤最后不足5个元素的轮次,可加判断 if len(current_chunk) ==5: first, second, third, fourth, fifth = current_chunk # 基础打印 print(first, second, third, fourth, fifth) # 若需要和示例完全一致的带引号、逗号分隔格式,替换上面的print为下一行 # print(', '.join(f'"{item}"' for item in current_chunk))
方案2:itertools.batched 实现(Python 3.12+ 适用)
Python 3.12及以上版本内置了专门的分块迭代工具,语法更简洁:
from itertools import batched L = ["a","b","c","d","e","f","g","h","i","j"] for first, second, third, fourth, fifth in batched(L, 5): print(first, second, third, fourth, fifth)
内容的提问来源于stack exchange,提问作者jer_card
相关产品推荐
相关产品推荐

