如何根据索引子列表对groupbatch元素进行列表? 下面是应该考虑的可能情况.希望这会有更好的帮助.

长度为elements1st Instance :==所有indices个元素的总和

indices = [1, 3, 5]
elements = ['A','B','C','D','E','F','G','H','I']

Output:
[['A'], ['B','C','D'],['E','F','G','H','I']]

2nd Instance :elements的长度;全部indices个元素的总和

应考虑最大元素为indices,然后相应地分组elements列表

indices = [1, 3, 5]
elements = ['A','B','C','D','E','F','G','H','I', 'J','K','L','M','N']

Output:
[['A'], ['B','C','D'],['E','F','G','H','I'],['J','K','L','M','N']]

3rd Instance :elements的长度;全部indices个元素的总和

应考虑最大元素为indices,然后相应地分组elements列表

indices = [1, 3, 5]
elements = ['A','B','C','D','E','F','G','H','I', 'J','K','L']

Output:
[['A'], ['B','C','D'],['E','F','G','H','I'],['J','K','L']]

4th Instance :elements的长度;全部indices个元素的总和

应考虑最大元素为indices,然后相应地分组elements列表

indices = [1, 3, 5]
elements = ['A','B','C','D','E','F','G','H','I', 'J','K','L','M','N','O','P','Q','R','S']

Output:
[['A'], ['B','C','D'],['E','F','G','H','I'],['J','K','L','M','N'], ['O','P','Q','R','S']]

5th Instance :长度为elements;全部indices个元素之和

indices = [1, 3, 5]
elements = ['A','B','C']

Output:
[['A'], ['B','C']]

6th Instance :长度为elements;全部indices个元素之和

indices = [1, 3, 5]
elements = ['A','B','C','D','E','F']

Output:
[['A'], ['B','C','D'],['E','F']]

How can I achieve this in Python ?

推荐答案

您可以使用itertools.isliceelements进行切片:

from itertools import islice

indices = [1, 3, 5]
elements = ['A','B','C','D','E','F','G','H','I', 'J','K','L','M','N','O','P','Q','R','S']

def get_cnt(indices):
    if len(indices) == 0:
        return
    yield from indices
    while True:
        yield indices[-1]

out, it, g = [], iter(elements), get_cnt(indices)
while slice_:=list(islice(it, next(g))):
    out.append(slice_)

print(out)

打印:

[['A'], ['B', 'C', 'D'], ['E', 'F', 'G', 'H', 'I'], ['J', 'K', 'L', 'M', 'N'], ['O', 'P', 'Q', 'R', 'S']]

Python-3.x相关问答推荐

替换Pandas中组下的列值

PythonPandas -通过知道位置(Loc)而不是索引来删除行

网站抓取:当我使用Chrome DevTools中的网络选项卡时,找不到正确的URL来提供我想要的数据

如何检索与美汤相似的标签中的文本?

基于Pandas列动态创建分箱,以使观测值数量或计数占总计数的1%.

在 python 中使用正则表达式在行尾查找特定元素

matplotlib.pyplot 多边形,具有相同的纵横比和紧凑的布局

有没有办法使用重采样矢量化添加缺失的月份?

Python rolling_corr 取消后,应该用什么方法来处理

活动屏幕上的 PyQt4 中心窗口

如何通过python打开文件

numpy.ndarray 与 pandas.DataFrame

为什么我在 Python 中收到错误消息无法导入名称 NoneType?

tensorflow 中 numpy.newaxis 的替代方案是什么?

cv2 python 没有 imread 成员

如何在多核上运行 Keras?

变量类型注解NameError不一致

Windows 下 Python 3.x 的 OpenCV

Beautifulsoup 的单元测试失败

实例变量 Python 的类型提示约定