python - 如何通过 5 迭代元素:Python
问题描述
我有一个长度约为 90 的列表,我想进行迭代,以便每次迭代中的 5 个对象具有不同的值,在每次集成时,我都会打印以查看元素,如下所示:
L= ["a","b","c","d","e","f","g","h","i","j"]
loop....
print(first,second,third,fourth,fifth)
>>> "a" , "b" , "c" , "d" , "e" -> first iteration
>>> "f","g","h","i","j" -> second iteration
我该如何进行?
解决方案
如果您不确定list
可以使用的长度,请itertools.cycle
使用islice
如下所示:
import math
from itertools import cycle , islice
L = ["a","b","c","d","e","f","g","h"]
i = cycle(L)
slc = 5
for _ in range(math.ceil(len(L)/slc)):
print(list(islice(i,slc)))
输出:
['a', 'b', 'c', 'd', 'e']
['f', 'g', 'h', 'a', 'b']
如果您确定可以使用的长度itertools.islice
并获得您想要的内容,如下所示:
from itertools import islice
L = ["a","b","c","d","e","f","g","h","i","j"]
i = iter(L)
slc = 5
for _ in range(len(L)//slc):
print(list(islice(i,slc)))
输出:
['a', 'b', 'c', 'd', 'e']
['f', 'g', 'h', 'i', 'j']
推荐阅读
- highcharts - Highcharts shankey图百分比未显示
- html - 视频自动播放在某些 Safari 浏览器上不起作用
- php - 如何根据键名条件从集合中获取价值?
- c++ - MDI选项卡名称变回.../任务栏预览未选择
- python - 保持 robotsframework 关键字库中的应用程序实例处于活动状态
- javascript - 抽象 React Router Dom 后路由参数不起作用
- mysql - 有没有一种简单的方法可以根据mysql中的优先级为每个类别的每一行分配最高值?
- omnet++ - 错误:在数据报中找不到 TLV 选项
- visual-studio-code - Visual Studio Code - Task.Todo 扩展
- python - 打开一个命令窗口并使用 Python 将内容传递给它