Reverse equal sized blocks in a list

If I have a list:

[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3] 

My goal is to split it into equal sized pieces n, undo each piece, and then return the pieces in order. So, for the example above, for the 4th piece, I get:

[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3] 
[_________]  [_________] [________]  [______]
     |            |           |          | 
     1            2           3          4 (this is smaller than 4 but receives the same treatment)

                     ||

[4, 3, 2, 1,    4, 3, 2, 1,      4, 3, 2, 1,     3, 2, 1]

This is what I have:

n = 4
l = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3] 
chunks = [l[i : i + n] for i in range(0, len(l), n)]
print(chunks)
# [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3]]

for i in range(len(chunks)):
    chunks[i] = list(reversed(chunks[i])) # or chunks[i] = chunks[i][::-1]

from functools import reduce
out = list(reduce(lambda x, y: x + y, chunks))

print(out)
# [4, 3, 2, 1, 4, 3, 2, 1, 4, 3, 2, 1, 3, 2, 1]

I do not think this is very good. Is there any other way that uses python libraries better than this?

+4
source share
2 answers

How about using the following list:

[x for i in range(0,len(l),4) for x in reversed(l[i:i+4])]

or with a parameterized block size:

chunk = 4
[x for i in range(0,len(l),chunk) for x in reversed(l[i:i+chunk])]

This generates:

>>> [x for i in range(0,len(l),4) for x in reversed(l[i:i+4])]
[4, 3, 2, 1, 4, 3, 2, 1, 4, 3, 2, 1, 3, 2, 1]

for your list. Also, I think it is quite declarative ( reversed(..)indicates that you are changing, etc.)

+5
source

, , , for :

lst = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3]
chunk = 4

for i in range(0, len(lst), chunk):
    lst[i:i+chunk] = reversed(lst[i:i+chunk])

print(lst)
# [4, 3, 2, 1, 4, 3, 2, 1, 4, 3, 2, 1, 3, 2, 1]

, , out = lst[:] .

+1

Source: https://habr.com/ru/post/1682044/


All Articles