我想从列表中创建一个类似列表的结构。除了知道如何解决之外,我想知道是否有任何术语来描述这个过程。
更多例子:
l = [1,2]
target = [[1,2]]
l = [1,2,3]
target = [[1,2],[1,2,3]]
l = [1,2,3,4]
target = [[1,2],[1,2,3,4]]
l = [1,2,3,4,5]
target = [[1,2],[1,2,3],[1,2,3,4,5]]
l = [1,2,3,4,5,6]
target = [[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5,6]]
我想找到一种获得上述结构的方法。
答案 0 :(得分:1)
ls = ["a","b","c"]
ls2 = [ls[:2],ls[:]]
如果这是您正在寻找的
答案 1 :(得分:0)
一般方法:
target = []
l = [1, 2, 3]
for i in range(len(l)):
value_list = []
for b in range(i+1):
target.append(l[:i+1])
print target
近期编辑:
target = []
l = [1, 2, 3]
for i in range(1, len(l)):
value_list = []
for i in range(i+1):
value_list.append(l[i])
target.append(value_list)
print target
答案 2 :(得分:0)
使用Python3.4:
if len(l)-1 <= 2:
t = [l[:2+i] for i in range(len(l)-1)]
else:
t = [l[:2+i] for i in range(len(l)-1)]
t.pop(-2)
print (t)
基于Stefan Stefanov
回答,我认为这是我的一般方法。
答案 3 :(得分:0)
这个怎么样:
def calculate_result(input_list):
if input_list == [1,2]:
target = [1,2]
elif input_list == [1,2,3]:
target = [[1,2],[1,2,3]]
elif input_list == [1,2,3,4]:
target = [[1,2],[1,2,3,4]]
elif input_list == [1,2,3,4,5]:
target = [[1,2],[1,2,3],[1,2,3,4,5]]
elif input_list == [1,2,3,4,5,6]:
target = [[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5,6]]
else:
raise ValueError('Result for {} not specified.'.format(input_list))
return target