【问题标题】:Implement sliding window with three input variables, list, window size and forward move size using python?使用python实现具有三个输入变量,列表,窗口大小和向前移动大小的滑动窗口?
【发布时间】:2019-11-01 10:32:01
【问题描述】:

我有一个这样的列表,

  l=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

现在我想应用一个大小为 5 (n1) 的滑动窗口,但它会向前移动三步 (n2)。

如果 n1=5 和 n2=3,我正在寻找的期望输出是,

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

我可以使用以下代码,

[ thelist[x:x+size] for x in range( len(thelist) - size + 1 ) ]  # but this returns only one 
forward move.

如何将其移动超过 1 个?

我可以使用 for 循环,但执行时间会很长。

如何用更少的执行时间来实现它?

【问题讨论】:

标签: python list itertools sliding-window


【解决方案1】:

试试这个:

[thelist[x: x + 5] for x in range(0,len(thelist),3) if x + 5 <= len(thelist)]

输出:

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

【讨论】:

  • 我更喜欢[thelist[x:x + size] for x in range(0, len(thelist) - size + 1, step)],否则range 的停止参数是多余的。
猜你喜欢
  • 1970-01-01
  • 2014-10-29
  • 2013-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多