在每个步骤中从列表中切出大小为N的窗口

时间:2019-01-10 21:30:16

标签: python list

如果要分割以下列表,以5步说,我可以轻松做到:

l = list(range(20))
l[::5]

给予:

[0, 5, 10, 15]

但是,在每个步骤中选择大小为3(或尽可能多的可用项目)的居中窗口是最简单的方法吗?所以:

[0, 1, 4, 5, 6, 9, 10, 11, 14, 15, 16]

目前,我正在尝试类似的事情:

[[l[i-1],l[i],l[i+1]] for i in l[::5][1:]]

什至没有返回扁平化的列表。

1 个答案:

答案 0 :(得分:5)

在列表理解中使用列表切片:

const response = await fetch(url);
const total = Number(response.headers.get('content-length'));

const reader = response.body.getReader();
let bytesReceived = 0;
while (true) {
    const result = await reader.read();
    if (result.done) {
        console.log('Fetch complete');
        break;
    }
    bytesReceived += result.value.length;
    console.log('Received', bytesReceived, 'bytes of data so far');
}

概括地说,我们有

[y for i in range(0, len(l), 5) for y in l[max(i-1, 0):i+2]]
# [0, 1, 4, 5, 6, 9, 10, 11, 14, 15, 16]

使用window = 3 // 2 [y for i in range(0, len(l), 5) for y in l[max(i-window, 0):i+window+1]] # [0, 1, 4, 5, 6, 9, 10, 11, 14, 15, 16] itertoolsislice的另一个选项:

chain