假设我有一个列表
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]
帮助将不胜感激, 谢谢。
最佳答案
使用简单的列表推导式,遍历原始列表的长度。另外,我使用了变量名 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]]
关于python - 将列表拆分为大小递减的子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27101942/