首页 > 解决方案 > 如何通过 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

我该如何进行?

标签: pythonlist

解决方案


如果您不确定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']

推荐阅读