【发布时间】:2020-08-21 10:24:23
【问题描述】:
我正在为这个小问题而烦恼,我确信可以(并且应该)递归地解决这个问题。
# split list in sublists based on length of first element.
list = [3, 1, 2, 3, 4, 1, 2, 3, 4]
#* #*
# *number of elements of the sublist
显示比解释更好,以上结果应该是:
[[1, 2, 3], [1, 2, 3, 4]]
我正在处理的列表总是遵循这个逻辑,第一个元素总是后面 n 个元素的长度。
编辑:
根据一些建议,我只是添加了一个 yield 来懒惰地完成它。
def split(ls):
"""
func that given a list extracts sub lists with the length indicated by the first element
[2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4] => [[1, 2], [1, 2, 3], [1, 2, 3, 4]]
"""
res = []
while ls:
dim = ls[0]
yield ls[1:dim + 1]
ls = ls[dim + 1:]
return res
>>> list(split([2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4]))
[[1, 2], [1, 2, 3], [1, 2, 3, 4]]
【问题讨论】:
-
到目前为止你有什么尝试??你必须表现出某种努力
-
这很容易出错。确定子列表长度的值必须完全正确。您所要求的仅适用于非常特定类型的列表。
标签: python list recursion multidimensional-array split