简体   繁体   English

从Clojure中的Collection(地图列表)中获取偶数/奇数索引元素

[英]get even/odd indexed elements from a Collection(List of Maps) in Clojure

I have a List of Map, I need to get the even/odd indexed elements from that list in Clojure. 我有一个Map List,我需要在Clojure中从该列表中获取偶数/奇数索引元素。 I don't want to iterate thought the list with for loop. 我不想迭代思考列表与for循环。 Is there any small or single_word function? 有没有small或single_word函数?

user=> (take-nth 2 [0 1 2 3 4 5 6 7 8 9])
(0 2 4 6 8)
user=> (take-nth 2 (rest [0 1 2 3 4 5 6 7 8 9]))
(1 3 5 7 9)

I do not know of any built-in function for this, but it is not that verbose to write one yourself, here is my attempt: 我不知道有任何内置功能,但是自己写一个并不简单,这是我的尝试:

(defn evens-and-odds [coll]
  (reduce (fn [result [k v]]
            (update-in result [(if (even? k) :even :odd)] conj v))
          {:even [] :odd []}
          (map-indexed vector coll)))

(evens-and­-odds [ "foo"­ "bar"­ "baz"­ "foob­ar" "quux­" ])
; -> {:even ["foo" "baz" "quux"], :odd ["bar" "foobar"]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM