[英]Implement sliding window with three input variables, list, window size and forward move size using python?
I have a list like this,我有一个这样的清单,
l=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
Now I want to apply a sliding window of size five (n1), but it will move forward by three steps(n2).现在我想应用一个大小为五(n1)的滑动 window,但它会向前移动三步(n2)。
The desired output I am looking for if n1=5 and n2=3 is,如果 n1=5 和 n2=3 我正在寻找所需的 output 是,
[1,2,3,4,5],[4,5,6,7,8],[7,8,9,10,11],[10,11,12,13,14],[13,14,15,16,17],[16,17,18,19,20]
I could use following code,我可以使用以下代码,
[ thelist[x:x+size] for x in range( len(thelist) - size + 1 ) ] # but this returns only one
forward move.
How to move it more than 1?如何移动它超过1?
I can use for loop, but execution time will be huge.我可以使用 for 循环,但执行时间会很长。
How to implement it with less execution time?如何以更少的执行时间来实现它?
Try this:尝试这个:
[thelist[x: x + 5] for x in range(0,len(thelist),3) if x + 5 <= len(thelist)]
Output: Output:
[[1, 2, 3, 4, 5],
[4, 5, 6, 7, 8],
[7, 8, 9, 10, 11],
[10, 11, 12, 13, 14],
[13, 14, 15, 16, 17],
[16, 17, 18, 19, 20]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.