ClojureDocs

导航

命名空间

zipmap

clojure.core

可在 1.0 版本使用 ()
  • (zipmap keys vals)
Returns a map with the keys mapped to the corresponding vals.
8 Examples
user=> (zipmap [:a :b :c :d :e] [1 2 3 4 5])
{:a 1, :b 2, :c 3, :d 4, :e 5}
;; 4 is not included in the result
user=> (zipmap [:a :b :c] [1 2 3 4])
{:a 1, :b 2, :c 3}

;; :c is not included in the result
user=> (zipmap [:a :b :c] [1 2])
{:a 1, :b 2}
user=> (pprint 
         (zipmap [:html :body :div] (repeat {:margin 0 :padding 0})))
{:html {:margin 0, :padding 0},
 :body {:margin 0, :padding 0},
 :div {:margin 0, :padding 0}}
;; transform a CSV file to an array of maps using the header line as keys
user=> (defn csv-map
  "ZipMaps header as keys and values from lines."
  [head & lines]
    (map #(zipmap (map keyword head) %1) lines))

user=> (apply csv-map [["FirstName", "LastName"], ["John", "Doe"], ["Jill", "Doh"]])
({:FirstName "John", :LastName "Doe"}, {:FirstName "Jill", :LastName "Doh"})
;; initialize with 0 for all values
user=> (zipmap [:a :b :c] (repeat 0))
{:a 0, :b 0, :c 0}
;; Note that if the keys are not unique, you can potentially lose data:
user=> (zipmap [:a :b :c :a] [1 2 3 4])
{:a 4, :b 2, :c 3}
;; Note the generated map is meant to be un-ordered and can be noticed only for sizes greater than 8

;; Ordered as key coll argument
user=> (zipmap [:key1 :key2 :key3 :key4 :key5 :key6 :key7 :key8] [1 2 3 4 5 6 7 8])
{:key1 1, :key2 2, :key3 3, :key4 4, :key5 5, :key6 6, :key7 7, :key8 8}

;; Un-ordered
user=> (zipmap [:key1 :key2 :key3 :key4 :key5 :key6 :key7 :key8 :key9] [1 2 3 4 5 6 7 8 9])
{:key3 3, :key2 2, :key8 8, :key6 6, :key9 9, :key7 7, :key4 4, :key1 1, :key5 5}
;; Alternative logic for `cond` scenarios

;; `zipmap` returns a map paring each value in the range (1-4) to a percentage (50%)
(def rates
  (conj {0 0/100}
        (zipmap (range 1 5) (repeat 50/100))
        {5 90/100}))
;; => {0 0, 1 1/2, 2 1/2, 3 1/2, 4 1/2, 5 9/10}

(* 2.0 (rates 3))
;; => 1.0
See Also

Returns a lazy seq of the first item in each coll, then the second etc.

Added by mmwaikar

Returns a new coll consisting of to-coll with all of the items of from-coll conjoined. A transduce...

Added by KyleErhabor
1 Note
    By , created 6.1 years ago

    zipmap always leave last key & val if keys are duplicated like the last example code.

    You can know them from source code which assoc key & val to result map in left-to-right order.