Python:如何将列表拼接为给定长度的子列表? [英] Python: how to splice a list into sublists of given lengths?

查看:49
本文介绍了Python:如何将列表拼接为给定长度的子列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

I want to splice the above list into sublists of length = [1, 2, 3, 1]. In other words, I want my output to look something like this:

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

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

where my first sublist is of length 1, the second sublist is of length 2, and so forth.

推荐答案

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

You can use itertools.islice here to consume N many elements of the source list each iteration, eg:

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:如何将列表拼接为给定长度的子列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆