简体   繁体   English

Python列表分为多个块(向后)

[英]Python list split into chunks (BACKWARDS)

I want to split a given python list into chunks, similar to the following link, but in reverse. 我想将给定的python列表拆分为多个块,类似于以下链接,但相反。

How do you split a list into evenly sized chunks in Python? 如何在Python中将列表分成大小均匀的块?

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

However I want backward_chunk([1,2,3],2) = [[1], [2,3]] 但是我想要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. 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 . 而且,请不要调用变量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 . 如果只想反转ORDER而不是列表本身,则在reverseTrue只产生data[n:n+size][::-1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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