我有一个像[3,9,14]
的列表,我正在尝试创建一个嵌套列表,使用[3,9,14]
的值作为每个嵌套列表increment 1 each step
的开头,直到它到达{{ 1}},这样最终的嵌套列表看起来像next end point - 1
。最好的方法是什么?
答案 0 :(得分:4)
>>> 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]]
答案 1 :(得分:1)
>>> 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]]
答案 2 :(得分:1)
l=[3,9,14]
data=[]
x=0
for i in l:
data.append(list(range(x,i)))
x=i
print(data)
答案 3 :(得分:1)
试试这个。
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)
答案 4 :(得分:0)
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)
答案 5 :(得分:0)
您可以尝试这样的事情:
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])))
输出:
[0, 1, 2]
[3, 4, 5, 6, 7, 8]
[9, 10, 11, 12, 13]