gpt4 book ai didi

Python:如何将列表拼接成给定长度的子列表?

转载 作者:太空宇宙 更新时间:2023-11-04 07:05:01 26 4
gpt4 key购买 nike

x = [2, 1, 2, 0, 1, 2, 2]

我想将上面的列表拼接成length = [1, 2, 3, 1]的子列表。换句话说,我希望我的输出看起来像这样:

[[2], [1, 2], [0, 1, 2], [2]]

我的第一个子列表的长度为 1,第二个子列表的长度为 2,依此类推。

最佳答案

您可以在此处使用 itertools.islice 每次迭代消耗源列表的 N 个元素,例如:

from itertools import islice

x = [2, 1, 2, 0, 1, 2, 2]
length = [1, 2, 3, 1]
# get an iterable to consume x
it = iter(x)
new_list = [list(islice(it, n)) for n in length]

给你:

[[2], [1, 2], [0, 1, 2], [2]]

关于Python:如何将列表拼接成给定长度的子列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55294735/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com