我如何获得序列的倒数第二个元素? Clojure 语言
How can i get the second to last element of a Sequence? Clojure
我知道如何使用 last 函数获取最后一个元素,但是是否有可能获取序列的倒数第二个元素?
(defn last
[args]
(last args))
(last [1 2 3 4]) ;;--> 4 but i want it to return 3
使用reverse, take-last, butlast or nth(这个好像是最快的):
(defn second-to-last1 [s]
(second (reverse s)))
(second-to-last1 (range 100))
=> 98
(defn second-to-last2 [s]
(first (take-last 2 s)))
(second-to-last2 (range 100))
=> 98
(defn second-to-last3 [s]
(last (butlast s)))
(second-to-last3 (range 100))
=> 98
(defn second-to-last4 [s]
(nth s (- (count s) 2) nil))
(second-to-last4 (range 100))
=> 98