将列表拆分为大小递减的子列表

时间:2014-11-24 09:53:19

标签: python list sublist

假设我有一个列表

list = [0,1,2,3]

如何将列表拆分为

之类的内容
new_list = [[0,1,2,3],[1,2,3],[2,3],[3]]

我尝试过使用:

def change(list):
    new_list = []
    for i in range(len(list)):
        total += [list:]
    return new_list

但是我得到了

的返回值
 new_list = [0,1,2,3,1,2,3,2,3,3]

非常感谢帮助, 感谢。

3 个答案:

答案 0 :(得分:4)

使用简单的列表推导,它遍历原始列表的长度。另外,我使用了变量名lst,因为list是python类型。

你走了:

>>> lst = [0,1,2,3]
>>> [lst[i:] for i in range(len(lst))]
[[0, 1, 2, 3], [1, 2, 3], [2, 3], [3]]

答案 1 :(得分:0)

newlist=[]
list = [0,1,2,3]
i=0
while i<len(list):
    newlist.append(list[i:])
    i=i+1

print newlist

答案 2 :(得分:0)

您还可以将maplambda

一起使用
 In [14]: map(lambda x: list[x:], xrange(len(list)))
 Out[14]: [[0, 1, 2, 3], [1, 2, 3], [2, 3], [3]]
相关问题