繁体   English   中英

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

[英]Python: how to splice a list into sublists of given lengths?

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

我想将上面的列表拼接成length = [1, 2, 3, 1] 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]]

基本上,我们要提取一定长度的子字符串。 为此,我们需要一个start_index和一个end_index。 end_index是您的start_index +我们要提取的当前长度:

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

res = []
start_index = 0
for length in lengths:
    res.append(x[start_index:start_index+length])
    start_index += length

print(res)  # [[2], [1, 2], [0, 1, 2], [2]]

将此解决方案添加到其他答案中,因为它不需要任何导入的模块。

您可以使用以下listcomp:

from itertools import accumulate

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

[x[i - j: i] for i, j in zip(accumulate(length), length)]
# [[2], [1, 2], [0, 1, 2], [2]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM