【问题标题】:get even/odd indexed elements from a Collection(List of Maps) in Clojure从 Clojure 中的集合(地图列表)中获取偶数/奇数索引元素
【发布时间】:2011-11-03 09:42:30
【问题描述】:

我有一个 Map 列表,我需要从 Clojure 中的该列表中获取偶数/奇数索引元素。 我不想用 for 循环迭代思想列表。有什么small或者single_word函数吗?

【问题讨论】:

    标签: java list dictionary clojure closures


    【解决方案1】:
    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)
    

    【讨论】:

    • 谢谢,我已经找到了,只是错过了几秒钟来发布答案!
    • 这正是我需要的!
    【解决方案2】:

    我不知道有任何内置函数,但是自己写一个并不那么冗长,这是我的尝试:

    (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"]}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-22
      • 2016-09-01
      • 2018-09-25
      • 2013-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多