python - 如何从列表列表中选择元素的滑动窗口?

标签 python python-3.x slice nested-lists sliding-window

假设我有以下列表:

x = [[1,2,3],[4,5,6],[7,8,9,10]]

我希望选择所有大小的“窗口”,例如n=4,交错距离,例如d=2:

    [[1,2,3],[4]]                # Starts at position `0`
        [[3],[4,5,6]]            # Starts at position `d`
              [[5,6],[7,8]]      # Starts at position `2d`
                    [[7,8,9,10]] # Starts at position `3d`

即我希望在窗口与子列表重叠的地方采用相交的“切片”。

我该怎么做?

最佳答案

如果你预先计算了一些索引,你可以用一个虚拟的单行重建任何窗口:

import itertools
import operator

def window(x, start, stop):
    first = indices[start][0]
    last = indices[stop-1][0]
    return [
        [x[i][j] for i, j in g] if k in (first, last) else x[k]
        for k, g in itertools.groupby(
            indices[start:stop],
            key=operator.itemgetter(0))
        ]

def flat_len(x):
    """Return length of flattened list."""
    return sum(len(sublist) for sublist in x)
n=4; d=2
x = [[1,2,3],[4,5,6],[7,8,9,10]]

indices = [(i, j) for i, sublist in enumerate(x) for j in range(len(sublist))]

for i in range(0,flat_len(x)-n+1,d):
    print(window(x,i,i+n,indices))

>>> [[1, 2, 3], [4]]
>>> [[3], [4, 5, 6]]
>>> [[5, 6], [7, 8]]

关于python - 如何从列表列表中选择元素的滑动窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56110350/

相关文章:

python - 在 Python 中访问类中静态方法的惯用方法

java - 使用 .toPandas() 函数时如何修复 Py4JJavaError?

Python OpenCv,只读取图像的一部分

python - 如何打印列表的某些部分?

python - 是否有等同于 (i+1)%N 的 Python 切片符号?

python - 切片时的 if 语句

python - 具有多个列表的列表理解中的 If 语句

python - Pandas 上的 Pip 安装失败?

imp.new_module() 的 Python importlib 模拟

python - 如何替换python列表特定索引处的值?