我一直在尝试惯用地循环嵌套向量,如下所示:
[[:a 1 :b 1 :c 1] [:a 1 :b 1 :c 3] [:a 1 :b 1 :c 1]]
一旦找到值,我还需要返回坐标。
例如调用 (find-key-value 3) 应返回 [1 2]
这是我到目前为止所拥有的,但它没有给我所需的输出,它会返回([] [] [] [] [] [1 2] [] [] [])
其中我只需要 [1 2]
(defn find-key-value
[array value]
(for [x (range 0 (count array))]
(loop [y 0
ret []]
(cond
(= y (count (nth array x))) [x y]
:else (if (= value (get-in array [x y]))
(recur (+ 1 y) (conj ret [x y]))
(recur (+ 1 y) ret))))))
任何人对我如何修复代码以获得我想要的解决方案或有更好的方法有任何想法!
最佳答案
列表推导式可用于查找满足谓词的所有值的坐标:
(defn find-locs [pred coll]
(for [[i vals] (map-indexed vector coll)
[j val] (map-indexed vector vals)
:when (pred val)]
[i j]))
(find-locs #(= 3 %) [[:a 1 :b 1 :c 1] [:a 1 :b 1 :c 3] [:a 1 :b 1 :c 1]])
=> ([1 5])
(find-locs zero? [[0 1 1] [1 1 1] [1 0 1]])
=> ([0 0] [2 1])
提出的问题似乎暗示应忽略输入中的关键字,在这种情况下,答案将变为:
(defn find-locs-ignore-keyword [pred coll]
(for [[i vals] (map-indexed vector coll)
[j val] (map-indexed vector (remove keyword? vals))
:when (pred val)]
[i j]))
(find-locs-ignore-keyword #(= 3 %) [[:a 1 :b 1 :c 1] [:a 1 :b 1 :c 3] [:a 1 :b 1 :c 1]])
=> ([1 2])
关于Clojure 嵌套 for 循环和索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67029321/