如何通过每次移动数组起始位置来从大数组派生多个小数组?
输入数组示例
[1,2,3,4,5,6,7,8,9,10]
输出:大小为3的多个子数组,从i=0,1,2,3开始.....
(1、2、3)(2、3、4)(3、4、5)(4、5、6)(5、6、7)(6、7、8)(7、8、9)(8、9、10)
我可以自己写代码
split(input){
i =0
results = []
while(i<len(input)-3):
start = i
end = i+ 3
subarray = input[start:end]
results.append(subarray)
}
return results
是否有一个python内置函数用于此,或sum lib?
不在标准库中,但这是一个很棒的包:使用more_itertools.windowed
:
l = [1,2,3,4,5,6,7,8,9,10]
# pip install more-itertools
from more_itertools import windowed
list(windowed(l, 3))
输出:
[(1, 2, 3),
(2, 3, 4),
(3, 4, 5),
(4, 5, 6),
(5, 6, 7),
(6, 7, 8),
(7, 8, 9),
(8, 9, 10)]
或与numpy
:
from numpy.lib.stride_tricks import sliding_window_view
sliding_window_view(l, 3).tolist()
输出:
[[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
[4, 5, 6],
[5, 6, 7],
[6, 7, 8],
[7, 8, 9],
[8, 9, 10]]
Try withzip
:
l = [1,2,3,4,5,6,7,8,9,10]
sublists = [list(zip(l,l[1:],l[2:]))]
>>> sublists
[[1, 2, 3],
[2, 3, 4],
[3, 4, 5],
[4, 5, 6],
[5, 6, 7],
[6, 7, 8],
[7, 8, 9],
[8, 9, 10]]
您可以通过列表推导和索引来实现这一点,如下所示:
k = 3
r = [1,2,3,4,5,6,7,8,9,10]
r_sublists = [r[i:i+k] for i in range(len(r) - k + 1)]
其中k为每个子列表中的项数。
您可以通过NumPy这样做:
import numpy as np
a = np.array([1,2,3,4,5,6,7,8,9,10])
np.lib.stride_tricks.sliding_window_view(a, 3)
# [[ 1 2 3]
# [ 2 3 4]
# [ 3 4 5]
# [ 4 5 6]
# [ 5 6 7]
# [ 6 7 8]
# [ 7 8 9]
# [ 8 9 10]]
如何使用列表推导式:
l = [1,2,3,4,5,6,7,8,9,10]
n = 3 # No of elements in each list
list_of_l = [l[i:i+n] for i in range(len(l)-n+1)]
list_of_l
[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10]]