简体   繁体   中英

Clojure: filter list of maps by 2nd list

Got a list of maps like

({:a "a" :b "b" :c "c"}
 {:a "d" :b "e" :c "f"}
 {:a "g" :b "h" :c "i"}
 {:a "j" :b "k" :c "l"})

and a 2nd list like ("c" "i") .

I need to filter the list of maps by the 2nd lists entries for a result like as

({:a "a" :b "b" :c "c"} {:a "g" :b "h" :c "i"})

but dont get a clue how.

Given

(def data
   (list
     {:a "a" :b "b" :c "c"}
     {:a "d" :b "e" :c "f"}
     {:a "g" :b "h" :c "i"}
     {:a "j" :b "k" :c "l"}))

Then

=> (filter (comp (set (list "c" "i")) :c) data)
({:a "a", :b "b", :c "c"} {:a "g", :b "h", :c "i"})
  • Your lists need list as the operator (or to be quoted).
  • I assume you want to filter by the value for key :c , which need not be the second entry in the printed map.

You need to get to grips with two or three aspects of Clojure:

  • How sequence functions like filter work.
  • Using sets and keywords as functions.
  • What comp does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM