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

标签 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]

帮助将不胜感激, 谢谢。

最佳答案

使用简单的列表推导式,遍历原始列表的长度。另外,我使用了变量名 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/

相关文章:

python - 将函数应用于 pandas groupby 数据框中的所有列

python - 扭曲 在客户端获取响应数据

python - 是否可以在 AWS Lambda 函数之间共享一段代码?

python - 通过循环将多个列表组装成一个列表

jquery - 使用 jQuery 在每 5 个 <li> 之后添加 </ul><ul>

python - Cython:将 2D 数组从 Python 传递到 C 并检索它

python - 为什么 range(0,10).remove(1) 不起作用?

python - 如何一次对两个列表的列表应用函数?

python - 计算在 python 中具有特定术语的子列表

python - 子列表到字典