Python 将列表转换为越来越大的块

Python 将列表转换为越来越大的块,python,list,Python,List,如何将列表转换为子列表大小不断增加的嵌套列表 比如说,, 从 到 我会使用原始列表的迭代器来完成这项工作。通过这种方式,我可以指定要采取的元素数量,而不必担心我目前处于哪个位置。此外,以下代码适用于任何iterable def increasing_chunks(iterable): it = iter(iterable) i = 1 while True: chunk = list(islice(it, i)) if not chunk

如何将列表转换为子列表大小不断增加的嵌套列表

比如说,, 从

我会使用原始列表的迭代器来完成这项工作。通过这种方式,我可以指定要采取的元素数量,而不必担心我目前处于哪个位置。此外,以下代码适用于任何iterable

def increasing_chunks(iterable):
    it = iter(iterable)
    i = 1

    while True:
        chunk = list(islice(it, i))
        if not chunk:
            break
        yield chunk
        i += 1
最后一个块可能被截断为迭代器剩下的任意数量的元素

演示:

如果要丢弃截断的块,请按如下方式调整代码:

def increasing_chunks_strict(iterable):
    it = iter(iterable)
    i = 1

    while True:
        chunk = list(islice(it, i))
        if len(chunk) < i:
            break
        yield chunk
        i += 1
有几项措施需要援救:

from itertools import count, accumulate as acc, takewhile as tw

lst = [1, 2, 3, 4, 5, 6]
[lst[c:c+i] for i, c in enumerate(tw(lambda x: x < len(lst), acc(count())), 1)]
# [[1], [2, 3], [4, 5, 6]]

假设列表长度具有正确的长度,以便最后一个块具有正确的大小,则可以使用列表总和、范围和,在几行中解决问题:

l = [1, 2, 3, 4, 5, 6]
slices = range(1, (len(l) + 1)/2 + 1)
result = [l[sum(slices[:s-1]):sum(slices[:s-1])+s] for s in slices]
作为后续行动,如果没有itertools,您需要跟踪索引:

l = [1, 2, 3, 4, 5, 6]

i, slice_length = 0, 1
result = []
while i < len(l):
    result.append(l[i:i + slice_length])
    i += slice_length
    slice_length += 1

print(result)
# [[1], [2, 3], [4, 5, 6]]

首先,假设列表的长度为n+1*n//2。你试过什么吗?到目前为止你试过什么?写一些代码。如何确定每个子数组的长度?列表[2,3,4]会被拆分为[2,3]、[4]?如果长度的顺序是1,2,3。。。如果最后一个元素不加起来会发生什么?这可能有助于适应:欢迎使用SO!目前尚不清楚该如何处理奇数长度的列表。请澄清。
>>> list(increasing_chunks_strict([1, 2, 3, 4, 5, 6]))
[[1], [2, 3], [4, 5, 6]]
>>> list(increasing_chunks_strict([1, 2, 3, 4, 5, 6, 7, 8]))
[[1], [2, 3], [4, 5, 6]]
from itertools import count, accumulate as acc, takewhile as tw

lst = [1, 2, 3, 4, 5, 6]
[lst[c:c+i] for i, c in enumerate(tw(lambda x: x < len(lst), acc(count())), 1)]
# [[1], [2, 3], [4, 5, 6]]
l = [1, 2, 3, 4, 5, 6]
slices = range(1, (len(l) + 1)/2 + 1)
result = [l[sum(slices[:s-1]):sum(slices[:s-1])+s] for s in slices]
l = [1, 2, 3, 4, 5, 6]

i, slice_length = 0, 1
result = []
while i < len(l):
    result.append(l[i:i + slice_length])
    i += slice_length
    slice_length += 1

print(result)
# [[1], [2, 3], [4, 5, 6]]