Warm tip: This article is reproduced from serverfault.com, please click

其他-使用Clojure中的给定步骤遍历列表

(其他 - Iterate over a list with a given step in clojure)

发布于 2020-11-28 02:53:53

我正在尝试使用Clojure中的给定步骤遍历列表。

在python中,我将执行以下操作:

xs = list(range(10))

xs[::2]
# out: [0, 2, 4, 6, 8]

xs[1::2]
# out: [1, 3, 5, 7, 9]

我想不出一种惯用的Clojure解决方案。

这是我能想到的最好的:

(defn iterate-step-2 [xs]
  (map first (take-while some? (iterate nnext xs))))

(iterate-step-2 (range 10))
; out: (0 2 4 6 8)

(iterate-step-2 (rest (range 10)))
; out: (1 3 5 7 9)

但是它不像python解决方案那样通用(步骤不可配置)并且没有那么灵活。另外,它似乎过于复杂。

有一个更好的方法吗 ?

Questioner
Tewfik
Viewed
11
Gwang-Jin Kim 2020-11-28 11:48:35
;; equivalent to Python's your_seq[1:7:2] would be:
(->> your-seq (drop 1) (take 7) (take-nth 2))

;; equivalent to Python's your_seq[::2] would be:
(->> your-seq (take-nth 2))

;; equivalent to Python's your_seq[2:4:-3] would be:
(->> your-seq (take 4) (drop 2) (reverse) (take-nth 3))

;; equivalent to Python's your_seq[2:-4:-1]:
(->> your-seq (take (+ 1 (- (length your-seq) 4))) (drop 2) (reverse))