首页 > 解决方案 > 在python中按列表的顺序重复选择n个项目

问题描述

假设我有一个很长的清单:

>>> import string
>>> my_list = list(string.ascii_lowercase)
>>> my_list
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] 

我想遍历这个列表并重复按顺序选择 n 个项目。例如,如果我想选择 5 个项目,那么它应该是:

step 1: ['a', 'b', 'c', 'd', 'e']
step 2: ['f', 'g', 'h', 'i', 'j']
step 3: ['k', 'l', 'm', 'n', 'o']
step 4: ['p', 'q', 'r', 's', 't']
step 5: ['u', 'v', 'w', 'x', 'y']
step 6: ['z', 'a', 'b', 'c', 'd']
step 7: ['e', 'f', 'g', 'h', 'i']
......

所以重点是:我想确保当我到达列表的最后一项时,第一项可以附加到最后一项并且循环继续进行。


为了将第一项附加到最后一项,我尝试过这样的事情:

def loop_slicing(lst_, i):
    """ Slice iterable repeatedly """
    if i[0] > i[1]:
        return [n for n in lst_[i[0]:]+lst_[:i[1]]]
    else:
        return lst_[i[0]:i[1]]

当我调用这个函数时,我可以这样做:

>>> loop_slicing(my_list, (0, 5))
['a', 'b', 'c', 'd', 'e']
>>> loop_slicing(my_list, (25, 4))
['z', 'a', 'b', 'c', 'd']

我可以在其中制作一个生成器,它可以生成 5 个序列号range(0, 26)以循环my_list并每次获取 5 个项目。

我不知道这是否是最好的方法。那么有没有更有效的方法来做这些事情呢?

标签: pythonpython-3.xlistiterator

解决方案


使用该itertools模块,您可以通过无限生成器循环和切片字符串:

from itertools import cycle, islice
from string import ascii_lowercase

def gen(x, n):
    c = cycle(x)
    while True:
        yield list(islice(c, n))

G = gen(ascii_lowercase, 5)

print(next(G))  # ['a', 'b', 'c', 'd', 'e']
print(next(G))  # ['f', 'g', 'h', 'i', 'j']
...
print(next(G))  # ['u', 'v', 'w', 'x', 'y']
print(next(G))  # ['z', 'a', 'b', 'c', 'd']

推荐阅读