返回序列中的重复项

Joe*_*ris 10 clojure sequence duplicates

我能想到的最好的是:

(defn dups [seq]
  (map (fn [[id freq]] id) 
       (filter (fn [[id freq]] (> freq 1))
               (frequencies seq))))
Run Code Online (Sandbox Code Playgroud)

有更简洁的方法吗?

Mat*_*ick 17

使用列表理解:

(defn dups [seq]
  (for [[id freq] (frequencies seq)  ;; get the frequencies, destructure
        :when (> freq 1)]            ;; this is the filter condition
   id))                              ;; just need the id, not the frequency
Run Code Online (Sandbox Code Playgroud)


ama*_*loy 14

(map key (remove (comp #{1} val) 
                 (frequencies seq)))
Run Code Online (Sandbox Code Playgroud)


Joe*_*ult 5

如果你想根据列表中项目的某些属性找到重复项(即它是一个地图列表或一个记录/ java对象列表)

(defn dups-with-function
  [seq f]
  (->> seq
       (group-by f)
       ; filter out map entries where its value has only 1 item 
       (remove #(= 1 (count (val %))))))

(let [seq [{:attribute    :one
            :other-things :bob}
           {:attribute    :one
            :other-things :smith}
           {:attribute    :two
            :other-things :blah}]]
  (dups-with-function seq :attribute))
Run Code Online (Sandbox Code Playgroud)

输出:

 ([:one
   [{:attribute :one, :other-things :bob}
    {:attribute :one, :other-things :smith}]])
Run Code Online (Sandbox Code Playgroud)

如果您有一个java对象列表,并且想要找到所有具有重复名字的对象:

(dups-with-function my-list #(.getFirstName %))
Run Code Online (Sandbox Code Playgroud)