seq 上的滑动窗口

发布于 2024-08-05 08:28:09 字数 116 浏览 3 评论 0原文

在 Clojure 中,在(有限的,不是太大的)seq 上设置滑动窗口的最好方法是什么?我应该只使用 droptake 并跟踪当前索引还是有更好的方法我错过了?

In Clojure, what would be the nicest way to have a sliding window over a (finite, not too large) seq? Should I just use drop and take and keep track of the current index or is there a nicer way I'm missing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

没︽人懂的悲伤 2024-08-12 08:28:09

我认为步骤 1 的 partition 可以做到这一点:

user=> (partition 3 1 [3 1 4 1 5 9])
((3 1 4) (1 4 1) (4 1 5) (1 5 9))

I think that partition with step 1 does it:

user=> (partition 3 1 [3 1 4 1 5 9])
((3 1 4) (1 4 1) (4 1 5) (1 5 9))
⊕婉儿 2024-08-12 08:28:09

如果你想在windows上操作,用map也可以很方便:

user=> (def a [3 1 4 1 5 9])
user=> (map (partial apply +) (partition 3 1 a))
(8 6 10 15)
user=> (map + a (next a) (nnext a))
(8 6 10 15)

If you want to operate on the windows, it can also be convenient to do this with map:

user=> (def a [3 1 4 1 5 9])
user=> (map (partial apply +) (partition 3 1 a))
(8 6 10 15)
user=> (map + a (next a) (nnext a))
(8 6 10 15)
来日方长 2024-08-12 08:28:09

我不知道 partition 可以做到这一点,所以我这样实现了

(defn sliding-window [seq length]
  (loop [result ()
         remaining seq]
    (let [chunk (take length remaining)]
      (if (< (count chunk) length)
        (reverse result)
        (recur (cons chunk result) (rest remaining))))))

I didn't know partition could do this so I implemented it this way

(defn sliding-window [seq length]
  (loop [result ()
         remaining seq]
    (let [chunk (take length remaining)]
      (if (< (count chunk) length)
        (reverse result)
        (recur (cons chunk result) (rest remaining))))))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文