问题
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