将列表拆分为单独但重叠的块 [英] Split list into separate but overlapping chunks
本文介绍了将列表拆分为单独但重叠的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个列表A
A = [1,2,3,4,5,6,7,8,9,10]
我想按以下顺序使用上面的列表创建一个新列表(例如B
).
I would like to create a new list (say B
) using the above list in the following order.
B = [[1,2,3], [3,4,5], [5,6,7], [7,8,9], [9,10,]]
即前三个数字为A[0,1,2]
,后三个数字为A[2,3,4]
,依此类推.
i.e. the first 3 numbers as A[0,1,2]
and the second 3 numbers as A[2,3,4]
and so on.
我相信numpy
中具有用于此类操作的功能.
I believe there is a function in numpy
for such a kind of operation.
推荐答案
只需将Python的内置列表推导与列表切片结合使用即可:
Simply use Python's built-in list comprehension with list-slicing to do this:
>>> A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> size = 3
>>> step = 2
>>> A = [A[i : i + size] for i in range(0, len(A), step)]
这为您提供了您想要的东西:
This gives you what you're looking for:
>>> A
[[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, 10]]
但是您必须写几行代码,以确保代码不会因大小/步长的空前值而中断.
But you'll have to write a couple of lines to make sure that your code doesn't break for unprecedented values of size/step.
这篇关于将列表拆分为单独但重叠的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文