将Python列表拆分为重叠块列表

时间:2016-04-13 01:21:53

标签: python

此问题类似于 Slicing a list into a list of sub-lists ,但在我的情况下,我想要包含每个上一个子列表的最后一个元素,作为下一个子列表中的第一个元素。并且必须考虑到最后一个元素总是至少有两个元素。

例如:

list_ = ['a','b','c','d','e','f','g','h']

3号子列表的结果:

resultant_list = [['a','b','c'],['c','d','e'],['e','f','g'],['g','h']]

4 个答案:

答案 0 :(得分:13)

answer you linked中的列表理解很容易通过简单地缩短"步骤"来支持重叠块。传递给范围的参数:

>>> list_ = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> n = 3  # group size
>>> m = 1  # overlap size
>>> [list_[i:i+n] for i in range(0, len(list_), n-m)]
[['a', 'b', 'c'], ['c', 'd', 'e'], ['e', 'f', 'g'], ['g', 'h']]

此问题的其他访问者可能无法使用输入列表(可切片,已知长度,有限)。这是一个基于生成器的解决方案,可以处理任意迭代:

from collections import deque

def chunks(iterable, chunk_size=3, overlap=0):
    # we'll use a deque to hold the values because it automatically
    # discards any extraneous elements if it grows too large
    if chunk_size < 1:
        raise Exception("chunk size too small")
    if overlap >= chunk_size:
        raise Exception("overlap too large")
    queue = deque(maxlen=chunk_size)
    it = iter(iterable)
    i = 0
    try:
        # start by filling the queue with the first group
        for i in range(chunk_size):
            queue.append(next(it))
        while True:
            yield tuple(queue)
            # after yielding a chunk, get enough elements for the next chunk
            for i in range(chunk_size - overlap):
                queue.append(next(it))
    except StopIteration:
        # if the iterator is exhausted, yield any remaining elements
        i += overlap
        if i > 0:
            yield tuple(queue)[-i:]

注意:wimpy.util.chunks发布此实施以来。如果您不介意添加依赖项,则可以pip install wimpy使用from wimpy import chunks而不是复制粘贴代码。

答案 1 :(得分:4)

more_itertools有一个用于重叠迭代的窗口工具。

<强>鉴于

finalize()

<强>代码

public class Main {
    public static void main(String... args) {
        new FOO().clone();
        new FOO().finalize();
    }

    interface ClonerFinalizer {
        default Object clone() {System.out.println("default clone"); return this;}
        default void finalize() {System.out.println("default finalize");}
    }

    static class FOO implements ClonerFinalizer {
        @Override
        public Object clone() {
            return ClonerFinalizer.super.clone();
        }
        @Override
        public void finalize() {
            ClonerFinalizer.super.finalize();
        }
    }
}

如果需要,您可以通过过滤窗口来删除import more_itertools as mit iterable = list("abcdefgh") iterable # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] 填充值:

windows = list(mit.windowed(iterable, n=3, step=2))
windows
# [('a', 'b', 'c'), ('c', 'd', 'e'), ('e', 'f', 'g'), ('g', 'h', None)]

有关None

的详细信息,另请参阅more_itertools docs

答案 2 :(得分:2)

>>> "Missing files for device : {0}".format(var).center(50)
'          Missing files for device : abc          '

答案 3 :(得分:2)

这是我想出的:

l = [1, 2, 3, 4, 5, 6]
x = zip (l[:-1], l[1:])
for i in x:
    print (i)

(1, 2)
(2, 3)
(3, 4)
(4, 5)
(5, 6)

Zip接受任意数量的可迭代项,还有zip_longest