Reputation: 1354
I have a list like [3,9,14]
and I'm trying to create a nested list using values of [3,9,14]
as the beginning of each nested list, increment 1 each step
until it reaches the next end point - 1
, such that the final nested list will look like [[0,1,2],[3,4,5,6,7,8],[9,10,11,12,13]]
. What's the best way to do this?
Upvotes: 0
Views: 62
Reputation: 12669
You could try something like this:
list_a=[3,9,14]
list_a.insert(0,0)
for i in range(0,len(list_a),1):
chunk=list_a[i:i+2]
if len(chunk)==2:
print(list(range(chunk[0],chunk[1])))
output:
[0, 1, 2]
[3, 4, 5, 6, 7, 8]
[9, 10, 11, 12, 13]
Upvotes: 0
Reputation: 31
Try this.
inputdata = [3,9,14]
outputdata = []
a =[]
b =[]
for i,value in enumerate(inputdata):
if i == 0:
a.append(value)
else:
a.append(value-inputdata[i-1])
for i,value in enumerate(a):
if i == 0:
data = [x for x in range(value)]
b.append(data)
else:
data = [x for x in range(value,inputdata[i])]
b.append(data)
Upvotes: 1
Reputation: 239
L = [3, 9, 14]
result = []
sub_list = []
counter = 0
for i in L:
sub_list = []
for j in range(counter, i):
sub_list.append(counter)
counter += 1
counter = i
result.append(sub_list)
print(result)
Upvotes: 0
Reputation: 159
l=[3,9,14]
data=[]
x=0
for i in l:
data.append(list(range(x,i)))
x=i
print(data)
Upvotes: 1
Reputation: 133544
>>> nums = [3,9,14]
>>> [list(g) for g in map(range, [0] + nums, nums)]
[[0, 1, 2], [3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13]]
Upvotes: 1
Reputation: 133544
>>> nums = [3,9,14]
>>> [list(range(x,y)) for x, y in zip([0] + nums, nums)]
[[0, 1, 2], [3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13]]
Upvotes: 4