【问题标题】:Python: how to splice a list into sublists of given lengths?Python:如何将列表拼接成给定长度的子列表?
【发布时间】:2019-03-22 07:25:41
【问题描述】:
x = [2, 1, 2, 0, 1, 2, 2]

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

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

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

【问题讨论】:

标签: python list


【解决方案1】:

你可以在这里使用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]]

【讨论】:

  • 谢谢。如果x = [2, '', '', 2, '', '', ''] 怎么办?我认为使用islice 并没有给出[[2], ['', ''], [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]]

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

【讨论】:

    【解决方案3】:

    你可以使用下面的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]]
    

    【讨论】:

      猜你喜欢
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多