是否有交换给定地图的键和值的功能。因此,给定一个地图,我希望键成为值,并为键值。
(swap {:a 2 b 4}) => {2 :a 4 :b}
一种方法是
(zipmap (vals my-map) (keys my-map))
但是想知道clojure是否为此提供了实用程序fn?
答案 0 :(得分:32)
这是map-invert
中clojure.set
的目的:
user=> (clojure.set/map-invert {:a 2 :b 4})
{4 :b, 2 :a}
答案 1 :(得分:5)
clojure.contrib.datalog.util中有一个函数reverse-map
,它实现为:
(defn reverse-map
"Reverse the keys/values of a map"
[m]
(into {} (map (fn [[k v]] [v k]) m)))
答案 2 :(得分:3)
对于以后阅读此内容的任何人,我认为以下内容应该会有所帮助。
反转地图可能会返回关系。如果地图是单射的(一对一),那么逆也将是一对一的。如果地图(好像经常是这种情况)是多对一的,那么你应该使用一个集合或向量。
地图的价值是唯一的
(defn invert-one-to-one
"returns a one-to-one mapping"
[m]
(persistent! (reduce (fn [m [k v]] (assoc! m v k)) (transient {}) m)))
(def one-to-one {:a 1 :b 2 :c 3})
> (invert-one-to-one one-to-one)
{1 :a 2 :b 3 :c}
地图的值不唯一。这是非常常见的 - 最安全地假设您的地图是这种形式......所以(def invert invert-many-to-one)
(defn invert-many-to-one
"returns a one-to-many mapping"
([m] (invert-many-to-one #{} m))
([to m]
(persistent!
(reduce (fn [m [k v]]
(assoc! m v (conj (get m v to) k)))
(transient {}) m))))
(def many-to-one {:a 1 :b 1 :c 2})
> (invert-many-to-one many-to-one)
{1 #{:b :a}, 2 #{:c}} ; as expected
> (invert-many-to-one [] many-to-one)
{1 [:b :a], 2 [:c]} ; we can also use vectors
> (invert-one-to-one many-to-one) ; what happens when we use the 'wrong' function?
{1 :b, 2 :c} ; we have lost information
值是集合/集合,但它们的交集始终为空。 (没有元素出现在两个不同的集合中)
(defn invert-one-to-many
"returns a many-to-one mapping"
[m]
(persistent!
(reduce (fn [m [k vs]] (reduce (fn [m v] (assoc! m v k)) m vs))
(transient {}) m)))
(def one-to-many (invert-many-to-one many-to-one))
> one-to-many
{1 #{:b :a}, 2 #{:c}}
> (invert-one-to-many one-to-many)
{:b 1, :a 1, :c 2} ; notice that we don't need to return sets as vals
值是集合/集合,并且至少存在两个交叉不为空的值。如果您的值是集合,那么最好假设它们属于此类别。
(defn invert-many-to-many
"returns a many-to-many mapping"
([m] (invert-many-to-many #{} m))
([to m]
(persistent!
(reduce (fn [m [k vs]]
(reduce (fn [m v] (assoc! m v (conj (get m v to) k))) m vs))
(transient {}) m))))
(def many-to-many {:a #{1 2} :b #{1 3} :c #{3 4}})
> (invert-many-to-many many-to-many)
{1 #{:b :a}, 2 #{:a}, 3 #{:c :b}, 4 #{:c}}
;; notice that there are no duplicates when we use a vector
;; this is because each key appears only once
> (invert-many-to-many [] many-to-many)
{1 [:a :b], 2 [:a], 3 [:b :c], 4 [:c]}
> (invert-many-to-one many-to-many)
{#{1 2} #{:a}, #{1 3} #{:b}, #{4 3} #{:c}}
> (invert-one-to-many many-to-many)
{1 :b, 2 :a, 3 :c, 4 :c}
> (invert-one-to-one many-to-many)
{#{1 2} :a, #{1 3} :b, #{4 3} :c} ; this would be missing information if we had another key :d mapping to say #{1 2}
您还可以在invert-many-to-many
示例中使用one-to-many
。
答案 3 :(得分:0)
这是一个可以使用reduce:
来解决问题的选项(reduce #(assoc %1 (second %2) (first %2)) {} {:a 2 :b 4})
这是一个函数
(defn invert [map]
(reduce #(assoc %1 (second %2) (first %2)) {} map))
调用
(invert {:a 2 b: 4})
然后是reduce-kv
(我认为更干净)
(reduce-kv #(assoc %1 %3 %2) {} {:a 2 :b 4})