Creating sequential sublists from a list

落爺英雄遲暮 提交于 2021-02-08 10:35:50

问题


I'm new here and to programming as well.

I don't know if I put the question right, but I have been trying to generate sublists from a list.

i.e

say if L = range(5), generate sublists from L as such [[],[0],[0,1],[0,1,2],[0,1,2,3],[0,1,2,3,4]].

Kindly assist. Thanks.


回答1:


Look at this:

>>> # Note this is for Python 2.x.
>>> def func(lst):
...     return map(range, xrange(len(lst)+1))
...
>>> L = range(5)
>>> func(L)
[[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4]]
>>>



回答2:


You can also generate the sublists you've asked for by using the below for loop.

>>> L = range(5)
>>> l = []
>>> for i in range(len(L)+1):
        l.append([j for j in range(i)])
>>> l
[[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4]]

Also you can create the sublists without an empty sublist as the starting sublist through the code:

>>> i = list(range(5))
>>> [i[:k+1] for k in i]
[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4]]


来源:https://stackoverflow.com/questions/19624665/creating-sequential-sublists-from-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!