如何将矢量映射到地图,将重复键值推入其中?
这是我的输入数据:
[[:a 1 2] [:a 3 4] [:a 5 6] [:b a b] [:b c d] [:b e f]] 我想将此映射到以下内容: {:a [[1 2] [3 4] [5 6]] :b [[a b] [c d] [e f]]} 这是我到目前为止: (defn- build-annotation-map [annotation & m] (let [gff (first annotation) remaining (rest annotation) seqname (first gff) current {seqname [(nth gff 3) (nth gff 4)]}] (if (not (seq remaining)) m (let [new-m (merge-maps current m)] (apply build-annotation-map remaining new-m))))) (defn- merge-maps [m & ms] (apply merge-with conj (when (first ms) (reduce conj ;this is to avoid [1 2 [3 4 ... etc. (map (fn [k] {k []}) (keys m)))) m ms)) 以上产生: {:a [[1 2] [[3 4] [5 6]]] :b [[a b] [[c d] [e f]]]} 我似乎很清楚问题出在merge-maps中,特别是传递给merge-with(conj)的函数,但是在我敲了一会儿之后,我已经准备好帮助我了. 我一般都是lisp的新手,特别是clojure,所以我也很欣赏那些没有专门针对这个问题的评论,还有我的风格,脑死亡构造等等.谢谢! 解决方案(无论如何,足够接近): (group-by first [[:a 1 2] [:a 3 4] [:a 5 6] [:b a b] [:b c d] [:b e f]]) => {:a [[:a 1 2] [:a 3 4] [:a 5 6]],:b [[:b a b] [:b c d] [:b e f]]} 解决方法(defn build-annotations [coll] (reduce (fn [m [k & vs]] (assoc m k (conj (m k []) (vec vs)))) {} coll)) 关于您的代码,最重要的问题是命名.首先,我不会,特别是在没有先了解您的代码的情况下,不知道注释,gff和seqname的含义.潮流也很模糊.在Clojure中,根据上下文,以及是否应该使用更具体的名称,通常会更多地调用剩余部分. 在你的let语句中,gff(第一个注释) (让[[first& more]注释] …) 如果你宁愿使用(休息注释),那么我建议使用next,因为如果它是空的,它将返回nil,并允许你写(if-not remaining …)而不是(if-not(seq剩余) )…). user> (next []) nil user> (rest []) () 在Clojure中,与其他lisps不同,空列表是真实的. This文章显示了惯用命名的标准. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |