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

4

假设我有以下列表的列表:

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`

我希望您能够理解,我需要在窗口与子列表相重叠的地方取交集。这与IT技术有关,以下是需要翻译的内容:

那么,我该如何做呢?


https://numpy.org/doc/stable/reference/generated/numpy.lib.stride_tricks.sliding_window_view.html#numpy.lib.stride_tricks.sliding_window_view - iacob
3个回答

4
如果您预先计算一些索引,就可以用一条虚拟的代码行重构任何窗口:
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]]

2
我会选择嵌套的for循环,尽管不太美观。这是"最初的回答"。
x = [[1,2,3],[4,5,6],[7,8,9,10]]

def window(x, n, offset):
    pos = 0
    res = []
    for l in x:
        # Skip `l` if offset is larger than its length 
        if len(l) + pos <= offset:
            pos += len(l)
            continue
        # Stop iterating when window is complete
        elif pos >= n + offset:
            break

        tmp = []
        for el in l:
            #if `el` is in window, append it to `tmp`
            if offset <= pos < n + offset:
                tmp.append(el)
            # Stop iterating when window is complete
            elif pos >= n + offset:
                break
            pos += 1
        res.append(tmp)
    return res

def flat_len(x):
    """Return length of flattened list."""
    return sum(len(sublist) for sublist in x)

n = 4
d = 2

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

2
另一种方法是实际使用平面列表,获取正确的窗口,但之后进行修复。 最终我妥协并使用了一点numpy,这样修复就更容易了。
x = [[1,2,3],[4,5,6],[7,8,9,10]]
from itertools import chain
import numpy as np
n = 4
d = 2
def custom_slider(x, n, d):
    x_shape = [len(l) for l in x]
    x_cumsum_shape = np.cumsum(x_shape) #this will come in handy for fixing slices later
    x_flat = list(chain.from_iterable(x))
    result = []
    for i in range(0, len(x_flat) - n + 1, d):
        #essentially get slice points, using the current index i to start. ignore negative or zero slices
        split_pts = (x_cumsum_shape - i)[x_cumsum_shape - i > 0] 

        #[i: i + n] gives the correct slice. use split points to correctly mimic original arrays
        temp = [list(item) for item in np.split(x_flat[i: i + n], split_pts) if item.size]

        result.append(temp) #could also turn function into generator by yielding instead
    return result

custom_slider(x, n, d)

输出:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接