python - 如何在两个方向(向前,向后)获取每个元素的值的滑动窗口?

标签 python python-3.x

我有一个这样的值列表,

lst = [1, 2, 3, 4, 5, 6, 7, 8]

期望输出 :
window size = 3
    1  # first element in the list
    forward = [2, 3, 4]
    backward = []

    2  # second element in the list
    forward = [3, 4, 5]
    backward = [1]

    3  # third element in the list
    forward = [4, 5, 6]
    backward = [1, 2]

    4  # fourth element in the list
    forward = [5, 6, 7]
    backward = [1, 2, 3]

    5  # fifth element in the list
    forward = [6, 7, 8]
    backward = [2, 3, 4]

    6  # sixth element in the list
    forward = [7, 8]
    backward = [3, 4, 5]

    7  # seventh element in the list
    forward = [8]
    backward = [4, 5, 6]

    8  # eight element in the list
    forward = []
    backward = [5, 6, 7]

让我们假设窗口大小为 4,现在我想要的输出:

对于列表中的 each_element,我想要前面的 4 个值和后面的 4 个值,忽略当前值。

我能够使用它来获取值的滑动窗口,但这也没有给我正确的所需输出。
import more_itertools
list(more_itertools.windowed([1, 2, 3, 4, 5, 6, 7, 8], n=3))

最佳答案

代码:

arr = [1, 2, 3, 4, 5, 6, 7, 8]
window = 3
for backward, current in enumerate(range(len(arr)), start = 0-window):
    if backward < 0:
        backward = 0
    print(arr[current+1:current+1+window], arr[backward:current])
输出:
[2, 3, 4], []
[3, 4, 5], [1]
[4, 5, 6], [1, 2]
[5, 6, 7], [1, 2, 3]
[6, 7, 8], [2, 3, 4]
[7, 8], [3, 4, 5]
[8], [4, 5, 6]
[], [5, 6, 7]
一个类轮:
print(dict([(e, (lst[i+1:i+4], lst[max(i-3,0):i])) for i,e in enumerate(last)]))
输出:
{1: ([2, 3, 4], []),
 2: ([3, 4, 5], [1]),
 3: ([4, 5, 6], [1, 2]),
 4: ([5, 6, 7], [1, 2, 3]),
 5: ([6, 7, 8], [2, 3, 4]),
 6: ([7, 8], [3, 4, 5]),
 7: ([8], [4, 5, 6]),
 8: ([], [5, 6, 7])}
信用:感谢@FeRD 和@Androbin 的建议,解决方案现在看起来更好

关于python - 如何在两个方向(向前,向后)获取每个元素的值的滑动窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62316405/

相关文章:

python - 类型错误 : unsupported operand type(s) for/: 'Image' and 'int'

python - 在css选择器beautifulsoup python中转义 "["

python - 为 os.DirEntry 添加类型提示

python - 如何使用 `input_fn` 和 `read_batch_examples` 设置来创建 `num_epochs`?

python - 我应该如何在Python中使用自定义方法发送HTTP请求

python-3.x - 以 id 作为键,将多个标签读取为列表或字典中的元组,即 {id :(cat1, cat2,.....)}

python - 在 python 3.5 中,当使用参数列表作为 subprocess.Popen() 的输入时,我无法获得正确的 len(sys.argv)

Python 列表问题

python - 如何在spark中按多个键分组?

python - Pyppeteer: {'waitUntil' : 'networkidle0' } 不等到页面加载完毕