简体   繁体   中英

Python list split into chunks (BACKWARDS)

I want to split a given python list into chunks, similar to the following link, but in reverse.

How do you split a list into evenly sized chunks in Python?

Currently forward_chunk([1,2,3],2) = [[1,2], [3]]

However I want backward_chunk([1,2,3],2) = [[1], [2,3]]

# what I currently have
def forward_chunk(list, size):
    for i in range(0, len(list), size):
        yield list[i:i+size]

I cannot for the life of me make all the ranges and list slices work in order to achieve the backward dream. Anyone have any ideas?

Sth. like this maybe:

def backward_chunk(l, size):
    start = 0
    for end in range(len(l)%size, len(l)+1, size):
        yield l[start:end]
        start = end

> list(backward_chunk([1, 2, 3], 2))
[[1], [2, 3]]

The first chunk size is calculated as the modulo of list length and general chunk size. And please, don't call variables list .

Find how many extra elements there will be, split the list in two, yield the first piece, then do the chunk operation and yield the rest.

def forward_chunk(lst, size):
    piece = len(lst) % size
    piece, lst = lst[:piece], lst[piece:]
    yield piece
    for i in range(0, len(lst), size):
        yield lst[i:i+size]

You can use a normal chunk generator and reverse the list if you want.

def chunk(data, size, reverse=False):
    data = data[::-1] if reverse else data
    for n in range(0, len(data), size):
        yield data[n:n+size]

Example usage:

info = [1, 2, 3, 4, 5, 6, 7, 8]
for i in chunk(info, 4):
    print(i)  # => [1, 2, 3, 4], [5, 6, 7, 8]
for i in chunk(info, 4, True):
    print(i)  # => [8, 7, 6, 5], [4, 3, 2, 1]

If you want to only reverse the ORDER and not the list itself, just yield data[n:n+size][::-1] if reverse is True .

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