简体   繁体   中英

Python: slicing a list into a list of lists using list comprehension

I have a simple list like this:

mylist=[0,1,2,3,4,5,6,7,8,9]

which I want to slice creating a list of lists. The intended outcome is:

sliced=[[0],[0,1],[0,1,2],[0,1,2,3],...]


  1. First attempt: sliced=[mylist[i:i+n] for i in range(0, len(mylist), n)]

    wrong result: sliced=[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]


  1. Second attempt: sliced=[[mylist[l]] for l in range(0,10,1)]

    wrong result: sliced=[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]]


How should I handle this?

Like this?

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


Further reading: Explain Python's slice notation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM