python - 在python中按列表的顺序重复选择n项

标签 python python-3.x list iterator

假设我有一个长列表:

>>> 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']

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

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

最佳答案

使用 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']

关于python - 在python中按列表的顺序重复选择n项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50959718/

相关文章:

python - 如何去掉抓取数据的p标签

list - Haskell 递增元组的最后一个元素

python - 从 pandas dropna 中排除特定列

python - 如何在 matplotlib 中获取用户输入?

python - 在 Sklearn 的 SVC 中,当标签大小很大时,为什么训练时间与最大迭代不严格线性?

python - 在Python3中,如何使用.append函数将字符串添加到抓取的链接中?

python - 四处走走,python 中的 numpy 对象不匹配错误

python - 在两列中格式化 tkinter 消息框中的文本

c++ - 如何存储 while 循环中产生的数据?

python - 更改列表python中多个项目的值