python - 在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 个项目。
我不知道这是否是最好的方法。那么有没有更有效的方法来做这些事情呢?
解决方案
使用该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']
推荐阅读
- tensorflow - 如何从子目录加载张量流中的数据
- r - 在页面的剩余空间中垂直添加多个绘图
- python - 选择一个文本字符串
- javascript - 如何将带有内联文本样式的 JSON 转换为 html 文本样式?
- apache-spark - 如何检查 kubernetes 上 spark 的错误原因?
- python - 如何使用 Python (Selenium) 抓取画布元素
- javascript - 使用单选按钮一次将函数应用于单个 div
- javascript - jquery如何获取动态创建的每一行的索引
- c++ - 因超时而终止:优化的范围在哪里?
- swift - 流式传输显示、转换它并在窗口中显示它?