【问题标题】:Returning duplicates in a sequence返回序列中的重复项
【发布时间】:2011-11-08 20:23:37
【问题描述】:

我能想到的最好的是:

(defn dups [seq]
  (map (fn [[id freq]] id) 
       (filter (fn [[id freq]] (> freq 1))
               (frequencies seq))))

有没有更简洁的方法?

【问题讨论】:

  • 我喜欢您的解决方案,但只需将 (fn [[id freq]] id) 替换为键功能。

标签: clojure duplicates sequence


【解决方案1】:

使用列表推导:

(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

【讨论】:

    【解决方案2】:
    (map key (remove (comp #{1} val) 
                     (frequencies seq)))
    

    【讨论】:

    • 你能解释一下 (comp #{1} val) 在做什么吗?谢谢。
    • (comp #{1} val) 基本上意味着 (fn [x] (#{1} (val x))) - 基本上,它测试参数的 val 是否为 1(如果它是包含在包含数字 1) 的集合中。这里的 val 是频率对中的计数。
    【解决方案3】:

    如果您想根据列表中项目的某些属性查找重复项(即,它是地图列表或记录/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))
    

    输出:

     ([:one
       [{:attribute :one, :other-things :bob}
        {:attribute :one, :other-things :smith}]])
    

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

    (dups-with-function my-list #(.getFirstName %))
    

    【讨论】:

    • 感谢您回答我的问题:“在一系列地图中返回键 x 处的重复项”;-)
    【解决方案4】:

    完成这项工作的最小滤波器和频率单线器:

    (filter #(< 1 ((frequencies col) %)) col)
    

    但是它在大数据上表现不佳。您必须通过以下方式帮助编译器:

    (let [ freqs (frequencies col) ]
      (filter #(< 1 (freqs %)) col))
    

    【讨论】:

    • 您能否解释一下这如何/为什么对编译器有帮助?
    • 通过将频率计算放在词法上下文 let 子句中,您首先强制评估一次,而不是对集合中的每个项目进行评估(您可能希望编译器应该能够检测和避免)。
    【解决方案5】:

    some 是完美的功能。

    (defn dups [coll]
      (some (fn [[k v]] (when (< 1 v) k))
        (frequencies coll)))
    

    但是,它基本上与列表推导式相同。

    【讨论】:

      猜你喜欢
      • 2015-10-04
      • 2020-07-22
      • 2014-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多