python |给定每个索引的特定范围的数字,如何将主列表中的值分组到不同的列表中

标签 python arrays list indexing itertools

OGlist = [A, B, C, D, E, 1, 2, 3, 4, 5, F, G, H, I, J, 6, 7, 8, 9, 10]
_list = []
_list2 = []
所以,我有一个列表 OGlist...我希望 OGlist 的前 5 个元素进入 _list ,OGlist 的后 5 个元素进入 _list2,第三个 5 个元素进入 _list,第四个 5 个元素进入 _list2 等等
我如何实现这一目标?
我试过这个:
for x in range(1, len(OGlist) + 1):
    _list.append(OGlist[x-1])
    if x%5 == 0:
        y = x
        while True:
            _list2.append(OGlist[x])
            x += 1
            if x == y + 5:
                break
我应该使用什么条件和逻辑来获得所需的输出?
期望的输出:
_list = [A, B, C, D, E, F, G, H, I, J]
_list2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

最佳答案

我会这样处理:

from itertools import chain

_list = list(chain.from_iterable(OGlist[i:i+5] for i in range(0, len(OGlist), 10)))
_list2 = list(chain.from_iterable(OGlist[i:i+5] for i in range(5, len(OGlist), 10)))
OGlist[i:i+5] for i in range(0, len(OGlist), 10)返回类似 [[0, 1, 2, 3, 4], [10, 11, 12, 13, 14], ...] 的序列, chain.from_iterable将该列表列表连接成一个列表。

关于 python |给定每个索引的特定范围的数字,如何将主列表中的值分组到不同的列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65446180/

相关文章:

java - Spring /thymeleaf : How to fill a list in form and append another line to the form?

python - CSV 到 sqlite3 数据库。将列表从 Utf8 转换为 unicode

python - 需要在 pandas 的数据帧上聚合计数(rowid,colid)

python - 导入错误 : cannot import name 'QtCore'

python - 为什么 np.where & np.min 似乎不能正确处理这个数组?

c++ - 将迭代器中的数据插入列表的问题

python - Azure Functions 部署时无法运行

arrays - 快速计算数组数字输入?

javascript - 在函数中获取数组数据

java - GWT 中初始化不同的列表?