简体   繁体   中英

Slicing a list using List Comprehension

Let's say I want 20 integers from 1-20, put them in a list and for every 4 elements, group them. So I tried:

[(k[i::4]) for i in range(1,20)]

In theory, what I'm trying to do is for a range from 1-20, append i with step 4 into list k

It should look like [[1,2,3,4],[5,..,8]..[9,..,12].[13,..,16]...[17,..,20]

You can simply create more range objects:

>>> [list(range(i, i+4)) for i in range(1, 21, 4)]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]
>>>[list(range(i,i+4)) for i in range(1, 20, 4)]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]

Try the following:

>>> k = range(0, 21)
>>> [[k[i:i+4] for i in range(1, 20, 4)]][0]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]
>>> 
>>> k = range(1, 21)
>>> list(zip(*[iter(k)] * 4))
[(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16), (17, 18, 19, 20)]

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