我有一个这样的简单列表:
mylist=[0,1,2,3,4,5,6,7,8,9]
我想切片创建一个列表列表。预期的结果是:
sliced=[[0],[0,1],[0,1,2],[0,1,2,3],...]
首次尝试:
sliced=[mylist[i:i+n] for i in range(0, len(mylist), n)]
错误的结果:
sliced=[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
第二次尝试:sliced=[[mylist[l]] for l in range(0,10,1)]
错误的结果:
sliced=[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]
我该如何处理?
答案 0 :(得分:3)
喜欢这个吗?
>>> mylist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> sliced = [mylist[0:i] for i in range(1, len(mylist) + 1)]
>>> sliced
[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5, 6], [0, 1, 2, 3, 4, 5, 6, 7], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]