我有一个这样的价值 list ,

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

Desired Output:

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,现在是我想要的输出:

对于列表中的每个_元素,我希望前面有4个值,后面有4个值,忽略当前值.

我能够用它来获得滑动窗口的值,但这也没有给我正确的所需输出.

import more_itertools
list(more_itertools.windowed([1, 2, 3, 4, 5, 6, 7, 8], n=3))

推荐答案

Code:

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])

Output:

[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]

One Liner:

print(dict([(e, (lst[i+1:i+4], lst[max(i-3,0):i])) for i,e in enumerate(last)]))

Output:

{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-3.x相关问答推荐

在循环访问XML中的多个层时,xml.etree.Elementree Python3解析器不起作用

如何绘制交叉验证的AUROC并找到最佳阈值?

Numba编译时间呈指数级增长--可以像C编译器一样配置优化级别吗?

如何从选定的html内容中获取所需的文本

我无法直接在 VSCode 中运行该程序,但可以使用 VScode 中的终端运行它

Django在POST到外部URL时如何进行CSRF保护? 更新

在新数据帧上自动提取两个字符串 python 之间的相等性

无法使用 curve_fit() 在 python 中复制高斯函数的曲线拟合

有没有办法使用 python opencv 计算与图像的白色距离

在python中将字符串写入文本文件

Dask worker post-processing

Seaborn:注释线性回归方程

为什么 List 不能包含多种类型?

基本 Flask 应用程序未运行(TypeError:模块中缺少必填字段type_ignores)

用于 Django 应用程序的 Cython:它会工作吗?

在没有时间的python中创建日期

导入父目录进行简要测试

对字节进行按位运算

尾部斜杠的 FastAPI 重定向返回非 ssl 链接

如何在 Pandas 中的超 Big Data 框上创建数据透视表