Python如何将列表分为给定长度的子列表?

2021年4月5日16:00:03 发表评论 933 次浏览

列表拆分为子列表的问题非常普遍, 但拆分给定长度的子列表的问题并不常见。给定一个列表列表和一个长度列表, 任务是将列表分成给定长度的子列表。

例子:

Input : Input = [1, 2, 3, 4, 5, 6, 7]
        length_to_split = [2, 1, 3, 1]

Output: [[1, 2], [3], [4, 5, 6], [7]]

方法1:使用伊丽丝将列表分为给定长度的子列表是最优雅的方法。

# Python code to split a list
# into sublists of given length.
  
from itertools import islice
  
# Input list initialization
Input = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ]
  
# list of length in which we have to split
length_to_split = [ 2 , 1 , 3 , 1 ]
  
# Using islice
Inputt = iter ( Input )
Output = [ list (islice(Inputt, elem))
           for elem in length_to_split]
  
# Printing Output
print ( "Initial list is:" , Input )
print ( "Split length list: " , length_to_split)
print ( "List after splitting" , Output)

输出如下:

Initial list is: [1, 2, 3, 4, 5, 6, 7]
Split length list:  [2, 1, 3, 1]
List after splitting [[1, 2], [3], [4, 5, 6], [7]]

方法2:

使用

压缩

是将列表拆分为给定长度的子列表的另一种方法。

# Python code to split a list into
# sublists of given length.
from itertools import accumulate
  
# Input list initialization
Input = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]
  
# list of length in which we have to split
length_to_split = [ 2 , 2 , 3 , 3 ]
  
# Using islice
Output = [ Input [x - y: x] for x, y in zip (
           accumulate(length_to_split), length_to_split)]
  
# Printing Output
print ( "Initial list is:" , Input )
print ( "Split length list: " , length_to_split)
print ( "List after splitting" , Output)

输出如下:

Initial list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Split length list:  [2, 2, 3, 3]
List after splitting [[1, 2], [3, 4], [5, 6, 7], [8, 9, 10]]

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: